好友
阅读权限10
听众
最后登录1970-1-1
|
本帖最后由 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
-
forEach
userList,forEach(user ->{
//循环取值
//return 只是跳出本次循环和for循环的continue 一样效果
});
-
循环删除
Iterator it = userList.iterator();
while (it.hasNext()) {
User user = (User) it.next();
if (2 == user.getId()){
continue;
}
it.remove();
}
3.list转map toMap
- 二选一即可
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;
});
|
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|