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表达式的使用

posted @ 2021-07-24 16:38  edda_huang  阅读(1496)  评论(1编辑  收藏  举报