Stream.toMap

  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));

  

参考

stream介绍,以及lambda表达式的使用

原文地址:https://www.cnblogs.com/edda/p/15055564.html