开发手册 欢迎您!
软件开发者资料库

Java 使用Stream()过滤(filter)筛选List<T>列表数据并记录过滤的值日志方法代码

示例代码:List&lt;Person&gt; persons = Arrays.asList(new Person("John"), new Person("Paul"));1、使用filter()进行过滤筛选数据List&lt;Person&gt; filtered = persons.stre

示例代码

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);
}));