stream流Peek详解
总结:peek能做的map也能做。打印数据用peek,修改数据用map仅此而已
map:打印数据,修改数据等都能做。
peek:同上。但是更多用于观察流中数据。
区别:peek不需要返回,map需要返回
//peek:
List<TrackBusinessCodePO> duplicates = groupedMap.values().stream()
.filter(group -> group.size() > 1)
.flatMap(List::stream)
.peek(po -> {
String currentException = po.getException();
String newException = (currentException == null) ? exceptionMessage : currentException + ";" + exceptionMessage;
po.setException(newException);
})
.collect(Collectors.toList());
//map:
List<TrackBusinessCodePO> duplicates = groupedMap.values().stream()
.filter(group -> group.size() > 1)
.flatMap(List::stream)
.map(po -> {
String currentException = po.getException();
String newException = (currentException == null) ? exceptionMessage : currentException + ";" + exceptionMessage;
po.setException(newException);
return po;
})
.collect(Collectors.toList());
1:调试。 运行过程中,通过peek向控制台输出数据方便查看
我们有一个重复值的列表。我们将找到不同的值并使用peek方法进行调试。
List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
String output = list.stream()
.distinct()
.peek(e -> System.out.println("Debug value: " + e))
.collect(Collectors.joining(","));
System.out.println(output);
结果: Debug value: AA
Debug value: BB
Debug value: CC
AA,BB,CC
2:收集。 将流中的数据收集到其他集合中
public static void main(String[] args) {
List<String> debugList = new ArrayList<>();
List<String> names = Arrays.asList("Mahesh", "Suresh", "Mahendra");
names.stream()
.filter(el -> el.startsWith("M"))
.peek(e -> debugList.add(e))
.collect(Collectors.toList());
System.out.println(debugList);
}
结果:[Mahesh, Mahendra]