概述
I have a requirement to log/sysout the filtered values in Java Streams. I am able to log/sysout the non-filtered value using peek() method.
However, can someone please let me know how to log filtered values?
For example, let's say I have a list of Person objects like this:
List persons = Arrays.asList(new Person("John"), new Person("Paul"));
I want to filter out those persons who are not "John" as follows:
persons.stream().filter(p -> !"John".equals(p.getName())).collect(Collectors.toList());
However, I have to log the details of that "John" person which is filtered. Can someone please help me achieve this?
解决方案
If you want to integrate it with Stream API, there's not much you can do other than introducing the logging manually. The safest way would be to introduce the logging in the filter() method itself:
List filtered = persons.stream()
.filter(p -> {
if (!"John".equals(p.getName())) {
return true;
} else {
System.out.println(p.getName());
return false;
}})
.collect(Collectors.toList());
Keep in mind that introduction of side-effects to Stream API is shady and you need to be aware of what you're doing.
You could also construct a generic wrapper solution:
private static Predicate andLogFilteredOutValues(Predicate predicate) {
return value -> {
if (predicate.test(value)) {
return true;
} else {
System.out.println(value);
return false;
}
};
}
and then simply:
List persons = Arrays.asList(new Person("John"), new Person("Paul"));
List filtered = persons.stream()
.filter(andLogFilteredOutValues(p -> !"John".equals(p.getName())))
.collect(Collectors.toList());
...or even make the action customizable:
private static Predicate andLogFilteredOutValues(Predicate predicate, Consumer action) {
Objects.requireNonNull(predicate);
Objects.requireNonNull(action);
return value -> {
if (predicate.test(value)) {
return true;
} else {
action.accept(value);
return false;
}
};
}
then:
List filtered = persons.stream()
.filter(andLogFilteredOutValues(p -> !"John".equals(p.getName()), System.out::println))
.collect(Collectors.toList());
最后
以上就是凶狠自行车为你收集整理的根据java代码过滤记录,如何在Java Streams中记录过滤后的值的全部内容,希望文章能够帮你解决根据java代码过滤记录,如何在Java Streams中记录过滤后的值所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复