zl程序教程

您现在的位置是:首页 >  其他

当前栏目

java8 .stream().anyMatch / allMatch / noneMatch用法,判断某元素是否在list中,或某集合中全部都是某元素,或是否不在list中,统计list元素

List统计集合 用法 判断 是否 元素 stream
2023-06-13 09:13:59 时间

java8 stream接口终端操作 anyMatch,allMatch,noneMatch anyMatch:判断的条件里,任意一个元素成功,返回true

allMatch:判断条件里的元素,所有的都是,返回true

noneMatch:与allMatch相反,判断条件里的元素,所有的都不是,返回true

count方法,跟List接口中的 .size() 一样,返回的都是这个集合流的元素的长度,不同的是,流是集合的一个高级工厂,中间操作是工厂里的每一道工序,我们对这个流操作完成后,可以进行元素的数量的和;

如: public static void main(String[] args) {     List<Integer> list = Arrays.asList(1, 2, 1, 1, 1);     boolean anyMatch = list.stream().anyMatch(f -> f == (1));     boolean allMatch = list.stream().allMatch(f -> f == (1));     boolean noneMatch = list.stream().noneMatch(f -> f == (1));     long count = list.stream().filter(f -> f == (1)).count();     System.out.println(anyMatch);  // true     System.out.println(allMatch);  // false     System.out.println(noneMatch); // false     System.out.println(count);     // 4 }

其中判断条件可修改:

    boolean anyMatch = list.stream().anyMatch(f -> f.equals(1));

1.判断是否存在某个值 

//判断集合list中username是否存在张三这个值,存在返回true         boolean bool = list.stream().anyMatch(a->a.getUserName().equals("张三"));

2.过滤list中某个实体类的某个元素值

  //过滤集合list中含有username为张三的值,结果集为过滤后的集合(全是包含张三的对象)         List<Userinfo> data = list.stream().filter(a->a.getUserName().equals("张三"))                             .collect(Collectors.toList());          if(data!=null&&data.size()>0){              for (Userinfo userinfo:data) {                  System.out.println(userinfo.getUserName()+"------------"+userinfo.getPassword());              }          }

3.替换list中某个实体类的某个元素值 Bean bean1 = new Bean(1, 2);         Bean bean2 = new Bean(3, 4);         List<Bean> list = Lists.newArrayList(bean1, bean2);         System.out.println("list1 : " + list);         list.stream().filter(bean -> {             if (1 == bean.getNum1())                 bean.setNum1(2);             return true;         }).collect(Collectors.toList());         System.out.println("list2 : " + list);

4.收集集合中某个元素的值并逗号分割成字符串

String  productIds=crmProductList.stream().map(p->p.getId()).collect(Collectors.joining(","));