java8中 Collectors.toMap 详解
Java 8中的Collectors.toMap方法可以将Stream中的元素转换为一个Map对象。该方法有三个参数:keyMapper,valueMapper和mergeFunction。其中,keyMapper用于将Stream中的元素转换为Map的key,valueMapper用于将Stream中的元素转换为Map的value,mergeFunction用于处理当key重复时的冲突情况。
下面是一个例子,假设我们有一个List对象,其中包含多个Person对象,每个Person对象都有一个唯一的id属性和一个name属性。我们可以使用Collectors.toMap方法将List转换为一个以id为key,以Person对象为value的Map对象:
List<Person> personList = new ArrayList<>();
// 假设我们已经将多个Person对象添加到了personList中
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()));
在上面的例子中,Person::getId表示将Person对象的id属性作为Map的key,Function.identity()表示将Person对象本身作为Map的value。如果我们想要将Person对象的name属性作为Map的value,可以这样写:
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
如果我们的List中有重复的id,那么上面的代码将会抛出IllegalStateException异常。为了避免这种情况,我们可以使用mergeFunction参数来处理冲突。例如,如果我们想要将重复的id的Person对象合并为一个List,可以这样写:
Map<Integer, List<Person>> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Collections::singletonList, (list1, list2) -> {
List<Person> resultList = new ArrayList<>(list1);
resultList.addAll(list2);
return resultList;
}));
在上面的代码中,Collections::singletonList表示将Person对象转换为只包含一个元素的List,mergeFunction参数则表示将两个List合并为一个List。
相关推荐
















