- 遍历两个List匹配并合并(适用于两个Java类不相同的List想要合并到一个List)
public static List<Person> compareListHitData(List<Person> oneList, List<Identity> twoList) {
List<Person> list=oneList.stream().map(person -> twoList.stream().filter(identity -> Objects.equals(person.getEmployee(),identity.getNumber()))
.findFirst().map(i -> {
person.setDutyName(i.getDutyName());
person.setLoginNumber(i.getLoginName());
person.setUnit(i.getOrgNumber());
person.setMajor(i.getMain());
person.setOrderNumber(i.getOrder());
return person;
}).orElse(null))
.filter(Objects::nonNull).collect(Collectors.toList());
return list;
}
- 根据集合中对象的某一(多)属性将List转为Map
//当集合中多个对象这属性值相同时
Map<Long, List<Message>> collect = list.stream().collect(Collectors.groupingBy(r -> r.getId()));
//当集合中一个值对应一个对象时
Map<Long, Message> collect = list.stream().collect(Collectors.toMap(Message::getId, Function.identity()));
- 获取List中所有对象的某一属性值并转为List
List<Long> ids = list.stream().map(Message::getId).collect(Collectors.toList());
- List根据对象的某一属性去重并生成List
List<XXX> collect = list.stream() .collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(XXX::getCode))), ArrayList::new));
-根据List中对象某属性过滤并生成新List
List returnList =
list.stream().filter(r -> id.equals(r.getid())).collect(Collectors.toList());