public static void main(String[] args) {
List<EmpQuDaoOneAdmin> empQuDaoOneAdmins = new ArrayList<>();
EmpQuDaoOneAdmin dEmpQuDaoOneAdmin = new EmpQuDaoOneAdmin();
dEmpQuDaoOneAdmin.setEmpId(1L);
dEmpQuDaoOneAdmin.setEmpName(2L);
dEmpQuDaoOneAdmin.setQudaoOneId(0L);
empQuDaoOneAdmins.add(dEmpQuDaoOneAdmin);
EmpQuDaoOneAdmin dEmpQuDaoOneAdmin2 = new EmpQuDaoOneAdmin();
dEmpQuDaoOneAdmin2.setEmpId(1L);
dEmpQuDaoOneAdmin2.setEmpName(2L);
dEmpQuDaoOneAdmin2.setQudaoOneId(0L);
empQuDaoOneAdmins.add(dEmpQuDaoOneAdmin2);
List<QuDaoOne> quDaoOnes = new ArrayList<>();
QuDaoOne dQuDaoOne = new QuDaoOne();
dQuDaoOne.setId(0L);
dQuDaoOne.setEmps(Lists.newArrayList());
quDaoOnes.add(dQuDaoOne);
// 现根据 id 进行分组
Map<Long, List<EmpQuDaoOneAdmin>> empQuDaoOneAdminListMap = empQuDaoOneAdmins.stream()
.collect(Collectors.groupingBy(EmpQuDaoOneAdmin::getQudaoOneId));
// ----------------------方法一----------------------
quDaoOnes.parallelStream()
.forEach(quDaoOne -> {
List<EmpQuDaoOneAdmin> empQuDaoOneAdminList = empQuDaoOneAdminListMap.getOrDefault(quDaoOne.getId(), new ArrayList<>());
quDaoOne.getEmps()
.addAll(empQuDaoOneAdminList.stream()
.map(quDaoOneAdmin -> {
EmpQuDaoOneAdmin empQuDaoOneAdmin = new EmpQuDaoOneAdmin();
empQuDaoOneAdmin.setEmpId(quDaoOneAdmin.getEmpId());
empQuDaoOneAdmin.setEmpName(quDaoOneAdmin.getEmpName());
return empQuDaoOneAdmin;
}).collect(Collectors.toList())
);
});
System.out.println(quDaoOnes);
// ----------------------方法二----------------------
injection(empQuDaoOneAdmins, EmpQuDaoOneAdmin::getQudaoOneId, quDaoOnes, QuDaoOne::getId,
(empQuDaoOneAdmin, quDaoOne) -> {
EmpQuDaoOneAdmin empQuDaoOneAdmin2 = new EmpQuDaoOneAdmin();
empQuDaoOneAdmin2.setEmpId(empQuDaoOneAdmin.getEmpId());
empQuDaoOneAdmin2.setEmpName(empQuDaoOneAdmin.getEmpName());
quDaoOne.getEmps().add(empQuDaoOneAdmin2);
}
);
System.out.println(quDaoOnes);
}
public static <T, T2, R extends Serializable> void injection(List<T> aList, Function<T, R> mapper, List<T2> bList, Function<T2, R> mapper2, IConvert<T, T2> convert) {
aList.forEach(a -> {
List<T2> collect = bList.stream().filter(b -> Objects.equals(mapper.apply(a), mapper2.apply(b))).collect(Collectors.toList());
for (T2 t2 : collect) {
convert.accept(a, t2);
}
});
}
@FunctionalInterface
interface IConvert<T, T2> {
void accept(T t, T2 t2);
}
@Data
static class EmpQuDaoOneAdmin implements Serializable {
private Long empId;
private Long empName;
private Long qudaoOneId;
}
@Data
static class QuDaoOne implements Serializable {
private Long id;
private List<EmpQuDaoOneAdmin> emps;
}
java8两个List指定对象属性进行合并
最新推荐文章于 2024-09-13 10:34:03 发布