/** * */ package com.chuanglan.demo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; /** * @author Maq. * @createTime 2019年10月29日 下午4:33:38 * */ public class ListToMapDemo { public static void main(String[] args) { List<Student> list = new ArrayList<>( Arrays.asList( new Student("张三", 18, "b1"), new Student("王二", 20, "b2"), new Student("李四", 18, "b3") ) ); // 源码 // public static <T, K, U> // Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, // Function<? super T, ? extends U> valueMapper) { // return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new); // } Map<String, String> map = list.stream().collect(Collectors.toMap(Student::getName, Student::getGrade)); Map<String, Student> map2 = list.parallelStream().collect(Collectors.toMap(studen->{return studen.getName();}, stude->{return stude;})); //或者 //Map<String, Student> map2 = list2.stream().collect(Collectors.toMap(Student::getName, Function.identity())); Map<String, Integer> map3 = list.stream().collect(Collectors.toMap(item -> item.getName(), item -> item.getAge(),(oldVal, currVal) -> currVal,ConcurrentHashMap::new));
Map<String, Integer> map6 = list.stream().collect(Collectors.toMap(item -> "111", item ->2,(oldVal, currVal) -> currVal,ConcurrentHashMap::new));
map6.forEach( (k ,v)->{
System.out.println("k6: " + k + " v6:" + v);
});
map.forEach( (k ,v)->{ System.out.println("k: " + k + " v:" + v); }); map2.forEach( (k ,v)->{ System.out.println("k: " + k + " v:" + v.getAge()); }); //key冲突 错误信息java.lang.IllegalStateException: Duplicate key b3 List<Student> list2 = new ArrayList<>( Arrays.asList( new Student("张三", 18, "b1"), new Student("王二", 20, "b2"), new Student("李四", 18, "b3"), new Student("李四", 18, "b4") ) ); Map<String, Student> map4 = list2.stream().collect(Collectors.toMap(Student::getName, Function.identity(), (existing, replacement) -> existing)); //这样配置的话,发生冲突是existing会替代replacement //多个属性为key Map<String, Student> map5 = list2.stream().collect(Collectors.toMap(student -> student.getName()+student.getAge() , student->student, (existing, replacement) -> existing)); //这样配置的话,发生冲突是existing会替代replacement map4.forEach( (k ,v)->{ System.out.println("k: " + k + " v:" + v.getGrade()); }); map5.forEach( (k ,v)->{ System.out.println("k: " + k + " v:" + v.getGrade()); }); } }