Java List——lambda表达式的各种处理方式
根据某个属性分组
- 返回值:Map<key,List<>>
- 举例:根据userSex分组
Map<Integer, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getUserSex));
根据某个属性过滤
- 返回值:List<>
- 举例:查找男生(userSex == 1表示男生)
List<User> list = list.stream().filter(user -> user.getUserSex().toString().equals("1")).collect(Collectors.toList());
List转Map
- 返回值:Map
- 举例
Map<Long, User> userMap =
userList.stream().collect(Collectors.toMap(User::getId,User->User);
Map<Long, String> userMap =
userList.stream().collect(Collectors.toMap(User::getId,User::getUserName);
- 注意:如果集合对象有重复的key,会报错Duplicate key ....,可以用 (old,new)->old 来设置,如果有重复的key,则保留old,舍弃new
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, user -> user,(old,new)->old));
- 转换时,把list多个元素拼接作为map的key值
Map<Long, String> userMap =
userList.stream().collect(Collectors.toMap(user->user.getId()+"-"+user.getUserName(),user->user));
List排序
- 升序
list.sort(Comparator.comparing(User::getAge));
- 倒序
list.sort(Comparator.comparing(User::getAge).reversed());
提取List某一属性
- 返回值:List<>
- 举例
List<String> userNames = userList.stream().map(User::getUserName).collect(Collectors.toList());
List转Map时,List多个属性拼接作为Map的key
- 返回值:Map<>
- 举例
List查找出现次数最多的元素
- 返回值:元素类型
- 举例