乐猿社区,程序员的花果山程序员
/** * List -> Map * 比较优雅的写法是这样的 */ public static Map<Integer,User> getUser2MapUser2(List<User>userlist){ return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity())); }
/** * List -> Map * 重复key的状况下 简单的使用后者覆盖前者的 */ public static Map<Integer,User> getUser2MapUser3(List<User>userlist){ return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2)); }
/** * List -> Map * 指定map的具体实现 */ public static Map<Integer,User> getUser2MapUser4(List<User>userlist){ return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2, LinkedHashMap::new)); }
List里面的对象元素,以某个属性来分组,例如,以age分组,将age相同的放在一块儿:编程
Map<Integer, List<User>> groupBy = appleList.stream().collect(Collectors.groupingBy(User::getAge));
从集合中过滤出来符合条件的元素:api
//过滤出符合条件的数据 List<User> filterList = userList.stream().filter(a -> a.getName().equals("张三")).collect(Collectors.toList());
//计算 数量 int sum = appleList.stream().mapToInt(Apple::getNum).sum();
有了stream api后,对于list转换和循环方便太多了app
鼓励把新的Java8特性引入到目前的项目中,一个长期配合的团队以及一门古老的编程语言都须要不断的注入新活力,不然不进则退编程语言
[]ide