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