使用案例
将一个对象数组转为 Map 对象
import java.util.stream.Collectors;
import java.util.Arrays;
import java.util.HashMap;
public class ToMapDemo {
public static class Person {
private Integer id;
private String name;
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) {
// 对象数组
Person[] people = {
new Person(1, "张三"),
new Person(2, "李四"),
new Person(1, "王武")
};
// 1. 将数组转换为 集合对象
// 2. 将集合对象转换为 流对象;
// 3. 执行流的 terminal 类型操作将流对象转换为目标 Map 对象
HashMap<Integer, String> idToNameMap = Arrays.asList(people)
.stream()
.collect(Collectors.toMap(
Person :: getId,
Person :: getName,
(oldValue, newValue) -> newValue,
HashMap :: new
));
System.out.println(idToNameMap);
}
}
运行结果
函数参数说明
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, //
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapFactory)
- keyMapper:流中的每个数据将作为该方法的参数,该函数的输出结果将作为 Map 的键;
- valueMapper:流中的每个数据将作为该方法的参数,该函数的输出结果将作为 Map 的值;
- mergeFunction:当流中有两个数据 a,b,且有 keyMapper.apply(a) == keyMapper.apply(b) 时,最终生成的 Map 的值应该是 valueMapper.apply(a) 还是 valueMapper.apply(b);
- mapFactory:指明了生成 Map 的类型。