Collectors类的tomap方法将流收集到映射实例中。
list 转 map
collection.stream().collect(Collectors.toMap(User::getId, User::getName));
解决Key冲突
collection.stream().collect(Collectors.toMap(User::getAge, Function.identity(), (oldVal, newVal) -> newVal));
返回其他Map
collection.stream().collect(Collectors.toMap(User::getAge, Function.identity(), (oldVal, newVal) -> newVal, ConcurrentHashMap::new));
返回TreeMap
collection.stream() .sorted(Comparator.comparing(User::getName)) .collect(Collectors.toMap(User::getName, Function.identity(), (oldVal, newVal) -> newVal, TreeMap::new));