java8 lambda list map 便捷操作记录
作者:互联网
1.list的直接forEach
List<UserAccount> list = new ArrayList<>();
//{}内可以执行逻辑代码
list.forEach((UserAccount user) -> {
System.out.println(user.getId());
});
//只有一行代码时 {}可以省略
list.forEach((UserAccount user) -> System.out.println(user.getId()));
2.list int 排序
List<Integer> list = Arrays.asList(1, 2, 3, 9, 11, 6);
//正序
list.sort(Comparator.naturalOrder());
//倒序
list.sort(Comparator.reverseOrder());
3.list 对象 属性排序
List<UserAccount> list = new ArrayList<>();
//正序
list.sort(Comparator.comparing(UserAccount::getId));
//倒序
list.sort(Comparator.comparing(UserAccount::getId).reversed())
//正序流操作
List<UserAccount> collect = list.stream().sorted(Comparator.comparing(UserAccount::getId)).collect(Collectors.toList());
//倒序流操作
List<UserAccount> collect1 = listuserpaixu.stream().sorted((p1, p2) -> p2.getAddTime().compareTo(p1.getAddTime())).collect(Collectors.toList());
4.list 对象 根据对象属性过滤
//过滤 list中 用户邮箱为111的用户
List<UserAccount> lis = list2.stream().filter(user -> user.getEmail().equals("111")).collect(Collectors.toList());
//返回符合表达式的集合的第一个对象
Optional<UserAccount> first = list2.stream().filter(user -> user.getEmail().equals("111")).findFirst();
//防止空指针
first.ifPresent(a-> System.out.println(a));
5.list对象 根据对象的某个属性生成一个新的list
//获取邮箱字段集合
List<String> list = list.stream().map(UserAccount::getEmail).collect(Collectors.toList());
6.分组
//根据id分组
final Map<Integer, List<UserAccount>> collect = list.stream().collect((Collectors.groupingBy(UserAccount::getId)));
7.list 转 map
//map 的key 和value 都是属性值
Map<String, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName));
//key为属性 value为对象本身
Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, t->t));
//或
Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
//如果在转换的过程中, list对象的属性作为map的key时有重复 会报错,java.lang.IllegalStateException: Duplicate key
//可以用下面的方法解决
//1.拼接
Map<String, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName, (old,newK)->old+","+newK));
Map<String, User> map = list.stream().collect(Collectors.toMap(User::getId, t->t, (old, newK)->old+","+newK));
//或取新值或老值
Map<String, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getName, (old,newK)->newK));
Map<String, User> map = list.stream().collect(Collectors.toMap(User::getId, t->t, (old, newK)->newK));
//还可以排序 这里根据key排序 注意这里的返回值不同
TreeMap<String, User> collect = list.stream().collect(Collectors.toMap(User::getId, t->t, (old, newK)->newK, TreeMap::new));
待续....
标签:map,Collectors,stream,list,getId,collect,java8 来源: https://www.cnblogs.com/loveCrane/p/15918898.html