1.使用strean
List<Apple> details = new ArrayList<>();
List<Apple> counts = new ArrayList<>();
.......
List<Apple> results = details.stream().map(m1 -> {
counts.stream().filter(m2 -> Objects.equals(m1.getAppleId(), m2.getAppleId())).forEach(m2 -> {
m1.setAppleCount(m2.getAppleCount());
});
return m1;
}).collect(Collectors.toList());
2.使用parallelStream
List<Apple> details = new ArrayList<>();
List<Apple> counts = new ArrayList<>();
.......
List<Apple> results = details.parallelStream().map(m1 -> {
counts.parallelStream().filter(m2 -> Objects.equals(m1.getAppleId(), m2.getAppleId())).forEach(m2 -> {
m1.setAppleCount(m2.getAppleCount());
});
return m1;
}).collect(Collectors.toList());
3.使用map
List<Apple> details = new ArrayList<>();
List<Apple> counts = new ArrayList<>();
........
Map<String, Apple> map = new HashMap<>();
for(Apple detail : details) {
map.put(detail.getAppleId(), detail);
}
List<Apple> results2 = new ArrayList<>();
for(Apple count : counts){
Apple detail = map.get(count.getAppleId());
if (Objects.isNull(detail)) continue;
detail.setAppleCount(count.getAppleCount());
results2.add(detail);
}
效率对比:3 > 2 > 1