java8 Stream 流常用操作
1. map 映射
(1)对象赋值
List<User> userList = userService.getByIds(Ids);
List<UserRsp> rspList = userList.stream()
.map(item -> {
UserRsp rsp = new UserRsp ();
rsp.setName(item.getName());
rsp.setAge(item.getAge());
rsp.setSex(item.getSex());
return rsp;
}).collect(Collectors.toList());
(2)构造器赋值(代码更简洁)
List<UserRsp> userRspList =
userList.stream()
.map(item -> new UserRsp(item.getSex(), item.getName(), item.getAge()))
.collect(Collectors.toList());
(3) 取值收集
List<String> nameList= userList.stream()
.map(User::getName)
.collect(Collectors.toList());
2.flatMap
多个userList合并
List<Integer> ids = Arrays.asList(18,19,20,21,22);
List<User> userList= ids .stream()
.map(this::getUsersByAge)
.filter(Objects::nonNull)
.flatMap(List::stream)
.collect(Collectors.toList());
/**
* 通过年龄获取用户信息
* @param age 年龄
* @return userList
*/
public List<User> getUsersByAge(Integer age){
return userService.getByAge(age);
}
3.filter distinct
符合相关条件进行收集。
List<User> chapters = userList .stream()
.filter(Objects::nonNull)
.filter(item -> item.getAge()>10)
.distinct()
.collect(Collectors.toList());
4.sort
(1)
排序函数
List<User> users = userList.stream()
.sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());
(2)
自定义排序
Integer maxAge =20;
List<User> users = userList.stream()
.filter(item-> item.getAge() > maxAge)
.sorted(this::sortedAge)
.collect(Collectors.toList());
private int sortedAge(User a, User b) {
return a.getAge().compareTo(b.getAge());
}
5.groupBy
通过年龄进行分组
Map<Integer, List<User>> collect
= userList.stream()
.collect(Collectors.groupingBy(User::getAge));
6.转Map
获取用户名和用户性别
Map<String, String> typeMap = userList.stream()
.collect(Collectors.toMap(User::getName,User::getSex));
7.匹配
allMatch:流中每个元素都符合该条件时返回true;
anyMatch:流中任意一个元素满足该条件则返回true;
noneMatch:流中每个元素都不符合该条件时返回true;
findFirst:返回流中第一个元素;
findAny:返回流中的任意元素;
count:返回流中元素的总个数;
max:返回流中元素最大值;
min:返回流中元素最小值;
int maxAge = 10;
boolean allMatch = userList.stream().allMatch(item -> item.getAge() > maxAge );
boolean noneMatch = userList.stream().noneMatch(item -> item.getAge() > maxAge );
boolean anyMatch = userList.stream().anyMatch(item -> item.getAge() > maxAge );
Integer findFirst = userList.stream().findFirst().orElse(null);
Integer findAny = userList.stream().findAny().orElse(null);
long count = userList.stream().count();
Integer max = userList.stream().max(Comparator.comparing(User::getAge)).get();
Integer min = userList.stream().min(Comparator.comparing(User::getAge)).get();