示例代码:
List persons = Arrays.asList(new Person("John"), new Person("Paul"));
1、使用filter()进行过滤筛选数据
List filtered = persons.stream() .filter(p -> { if (!"John".equals(p.getName())) { return true; } else { System.out.println(p.getName()); return false; }}) .collect(Collectors.toList());
或
//使用包装器private static Predicate andLogFilteredOutValues(Predicate predicate) { return value -> { if (predicate.test(value)) { return true; } else { System.out.println(value); return false; } };}List persons = Arrays.asList(new Person("John"), new Person("Paul"));List filtered = persons.stream() .filter(andLogFilteredOutValues(p -> !"John".equals(p.getName()))) .collect(Collectors.toList());
2、collect()和Collectors.partitioningBy()进行过滤筛选数据
Map> map = persons.stream() .collect(Collectors.partitioningBy(p -> "John".equals(p.getName())));System.out.println("filtered: " + map.get(true));List result = map.get(false);
或
List result = persons.stream() .collect(Collectors.collectingAndThen( Collectors.partitioningBy(p -> "John".equals(p.getName())), map -> { System.out.println("filtered: " + map.get(true)); return map.get(false); }));