【笔记】jdk8 list常用特性方法笔记
本帖最后由 gdlove 于 2020-10-12 13:39 编辑## 1. 先定义公共list
~~~
//User(id,type,name)
List<User> userList = Arrays.asList(new User(1, 1, "张三"),
new User(2, 1, "李四"),
new User(3, 2, "王五"));
//不做此步迭代器循环删除时会报错
List<User> userList = new ArrayList<>(userList1);
~~~
## 2.最常用的循环 forEach
1. forEach
~~~
userList,forEach(user ->{
//循环取值
//return只是跳出本次循环和for循环的continue 一样效果
});
~~~
2. 循环删除
~~~
Iterator it = userList.iterator();
while (it.hasNext()) {
User user = (User) it.next();
if (2 == user.getId()){
continue;
}
it.remove();
}
~~~
## 3.list转maptoMap
1. 二选一即可
~~~
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Map<Integer, User> userMap1 = userList.stream().collect(Collectors.toMap(User::getId, user -> user));
~~~
2.取对象的属性值
~~~
Map<Integer, Integer> typeMap = userList.stream().collect(Collectors.toMap(User::getId, User::getType));
~~~
## 4.分组 groupingBy
~~~
//对象分组
Map<Integer, List<User>> map = userList.stream().collect(Collectors.groupingBy(User::getType));
//对象属性分组
Map<Integer, List<String>> map2 =userList.stream().collect(Collectors.groupingBy(User::getType, Collectors.mapping(User::getTname, Collectors.toList())));
~~~
## 5.排序 sorted
~~~
//根据Id升序排序
List<User> userListSortId = userList.stream().sorted(Comparator.comparing(User::getId)).collect(Collectors.toList());
//根据Id降序排序
List<User> userListSortId1 = userList.stream().sorted(Comparator.comparing(User::getId).reversed()).collect(Collectors.toList());
~~~
## 6.List属性判断 anyMatch、allMatch、noneMatch
~~~
//list任意一个User的id ==1 返回 true 否则返回false
//与之相对的方法时 noneMatch
boolean flag = userList.stream().anyMatch(user -> {
//判断条件
return user.getId() == 1;
});
//list所有User元素 的id == 1 返回true 否则返回false
boolean flag1 = userList.stream().allMatch(user -> {
//判断条件
return user.getId() == 1;
});
//list任意User的id == 1 返回 false 否则返回 true
boolean flag2 = userList.stream().noneMatch(user -> {
//判断条件
return user.getId() == 1;
});
~~~
优秀,感谢指点迷津,一直没用lamda,但是很想用哈哈,要好好学学了 学习学习 list这块还不是很熟悉,谢谢分享! java8 lamda 一下没有时间学习,不错, 一直在用,感觉还是挺方便的,代码简化的很可以,看着舒心 感觉楼主指点迷津 get,开始学jdk8了,很有用
页:
[1]