首先看一下下面这段代码
通常我们需要将一个list按照一定的规则聚合成一个map的时候,我们会这么写
Map<Long,Person> map = new HashMap<>();
for(Person person:testList) {
map.put(person.id,person);
}
但是函数式编程给我们提供了更简洁的写法。一句搞定,如下:
Map<Long,Person> map = testList.stream().collect(HashMap::new,(m, v) -> m.put(v.id,v),HashMap::putAll);
我们会想collect函数是如何做到的。
捞出collect函数签名研究一下:
/**
* Performs a <a href="package-summary.html#MutableReduction">mutable
* reduction</a> operation on the elements of this stream. A mutable
* reduction is one in which the reduced value is a mutable result container,
* such as an {@code ArrayList}, and elements are incorporated by updating
*