- List 根据某些属性进行去重
List<Order> orders = Lists.newArrayList();
// 按照订单编号和类型去重
orders = orders.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()
-> new TreeSet<>(Comparator.comparing(o -> o.getNum() + ";" + o.getType()))), ArrayList::new));
- List根据属性进行过滤
List<String> haveList = orders.stream().filter(o -> (o.getId.equals("sds"))).collect(Collectors.toList());
- List 提取某一属性,转换成对应的List
// 提取order的idList
List<String> orderIds = orders.stream().map(Order::getId).collect(Collectors.toList());
- 获取List 中时间字段最小的时间
List<TimeModel> targetTimes = targetService.getTodayTimeModelList();
Optional<LocalDateTime> optionalMinTime = targetTimes.stream().min(Comparator.comparing(TimeModel::getDateTime)).map(TimeModel::getDateTime);
LocalDateTime minTime = optionalMinTime.get();
- List 根据id,转换成map(分组)
//根据岗位Id,划分为map<postId, List<PersonPostModelVO>>
Map<String, List<PersonVO>> groupingMap = PersonList.stream().collect(Collectors.groupingBy(PersonVO::getPostId));
- 根据id,找到List对应的对象的下标(找不到返回-1)
int index = IntStream.range(0, orderList.size())
.filter(i -> entry.getKey().equals(orderList.get(i).getId()))
.findFirst().orElse(-1);
- 两List集合求差集
//new - old
List<SysPerson> addNormalList = newPersonList.stream()
.filter(w -> !oldPersonList.stream().map(SysPerson::getId).collect(Collectors.toList()).contains(w.getId()))
.collect(Collectors.toList());
- 实现多字段依次排序
//先age升序,再id降序
personList.stream().sorted(
Comparator.comparing(Person::getAge).thenComparing(-Person::getId)
).collect(Collectors.toList())
//先id升序,再时间降序
personList = personList.stream()
.sorted(Comparator.comparing(Person::getId)
.thenComparing(wl -> -wl.getCreatedTime().getTime())
)
.collect(Collectors.toList());
//上面的负号可能会报错,还可以采用下面方式,调用reversed方法
//code升序,id降序
Collections.sort(personList, Comparator.comparing(Person::getCode)
.thenComparing(Comparator.comparing(Person::getId).reversed()))
- 排序时传入自定义排序方法
//排下序(先按照状态排序,再按照修改时间排序)
result = result.stream().sorted(Comparator.comparing(BillHeaderVO::getStatus, (o1, o2)->{
…… }).thenComparing(BillHeaderVO::getDatetimeModified).reversed()).collect(Collectors.toList());
- String[] 转 List<Integer>
List<Integer> list = Arrays.asList(text.split(",")).stream()
.map(s -> Integer.parseInt(s)) //.map(Integer::valueOf)
.collect(Collectors.toList());
- List<对象> 转 Map
// 给出key重复时,使用哪个key作为主键,以下代码中的(oldKey, newKey) -> oldKey)代表oldKey和newKey键重复时返回oldKey对应的User
Map<Long, User> map = list.stream().collect(Collectors.toMap(User::getId, Function.identity(), (k1, k2) -> k1));
// 只返回对象里某个属性作为Value
Map<Long, String> map = list.stream().collect(Collectors.toMap(User::getId, User::getAge, (k1, k2) -> k1));
- 汇总
// BigDecimal
BigDecimal sum = list.stream().map(Order::getCost).reduce(BigDecimal.ZERO, BigDecimal::add);
// int、double、long等基础类型
Double sum = list.stream().mapToDouble(Student::getScore).sum();
欢迎补充和指正!