Jdk8 按照属性的某字段合并list

你好,我是猿java。

下面代码对比了传统方式和lambda方式对list的合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;

import java.util.ArrayList;
import java.util.Objects;

/**
* 按照 两个list中的对象的id一样进行合并,并且输出到一个新的list中
*/
public class TestClass {

// 传统方式
private List<PipelineJobAndRuntimeInfo> mergeData(List<PipelineJobEntity> jobs, List<JobRuntimeEntity> runtimes) {
List<PipelineJobAndRuntimeInfo> list = new ArrayList<>();
for (int i = 0; i < jobs.size(); i++) {

for (int j = 0; j < runtimes; j++) {

if (Objects.equals(jobs.get(i), runtimes.get(j))) {
PipelineJobAndRuntimeInfo info = new PipelineJobAndRuntimeInfo();
BeanUtils.copyProperties(jobs.get(i), info);
info.setJobId(jobs.get(i).getId());
info.setWorker(runtimes.get(j).getWorker());
info.setUpdatedAt(runtimes.get(j).getUpdatedAt());
}
}
}

}

// lambda写法
private List<PipelineJobAndRuntimeInfo> mergeData(List<PipelineJobEntity> jobs, List<JobRuntimeEntity> runtimes) {
List<PipelineJobAndRuntimeInfo> list;
list = jobs.stream().map(jobEntity -> {
PipelineJobAndRuntimeInfo info = new PipelineJobAndRuntimeInfo();
runtimes.stream().filter(runtimeEntity -> Objects.equals(jobEntity.getId(), runtimeEntity.getId())).forEach(runtimeEntity -> {
BeanUtils.copyProperties(jobEntity, info);
info.setJobId(jobEntity.getId());
info.setWorker(runtimeEntity.getWorker());
info.setUpdatedAt(runtimeEntity.getUpdatedAt());
});
return info;
}).collect(Collectors.toList());
return list;
}
}

本文为原创文章,转载请标明出处。

本文链接:https://www.yuanjava.cn/common/2022/04/20/java/merge.html

本文出自猿 java的博客

学习交流

如果你觉得文章有帮助,请帮忙转发给更多的好友,或关注公众号:猿java,持续输出硬核文章。

drawing