You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Stream中如何添加OR条件过滤非数字或长度非6的字符串?

解决方法

你当前的代码里,两个连续的filter方法是逻辑与(AND)关系,只有同时满足两个条件的元素才会被保留。要实现逻辑或(OR),只需要把两个判断条件合并到同一个filter中,用||运算符连接即可。

修改后的代码如下:

List<String> teList = new ArrayList<String>();
teList.add("123456");
teList.add("76543W");
teList.add("123R56");
teList.add("888888");
teList.add("7652");
teList.add("222222222222");
teList.add("1234526R");
teList.add("76543222R");

List<String> exlist = teList.stream()
    .filter(s -> !s.matches("[0-9]+") || s.length() != 6)
    .collect(Collectors.toList());
System.out.println(exlist.toString());

逻辑说明

  • !s.matches("[0-9]+"):判断字符串不是纯数字
  • s.length() != 6:判断字符串长度不等于6
  • ||:逻辑或运算符,只要满足其中一个条件,该字符串就会被保留

运行这段代码后,输出结果会排除掉"123456"和"888888"(这两个是纯数字且长度为6),其余所有元素都会被保留。

内容的提问来源于stack exchange,提问作者Rahul SK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 00:24:17