首页 > 解决方案 > 根据结果​​数据组合两个列表以在 java 8 中创建一个新列表

问题描述

我想根据某些标准将两个列表组合成一个列表。示例是列表 1 包含

final Org ro1= new Org(1, 1001, "Name 01");
final Org ro2 = new Org (2, 1001, "Name 02");
final Org ro3 = new Org (3, 1002, "Name 03");
final Org ro4 = new Org (4, 1003, "Name 04");
final Org ro5 = new Org (5, 1004, "Name 05");
List<Org> listOrg = new ArrayList<>();
// Add all the object to the listOrg 

清单 2 包含

final Candidate can1 = new Candidate(1001, "Candidate01", "100");
final Candidate can2 = new Candidate(1002, "Candidate02", "150");
final Candidate can3 = new Candidate(1003, "Candidate03", "200");
List<Candidate > listCandidate  = new ArrayList<>();
// Add all the Candidate  object to the listCandidate  

我的最终清单看起来像

List<Result > listResult  = new ArrayList<>();
// Each individual object of the listResult is followed- 
final Result rs1= new Result (1, 1001, "Name 01", "Candidate01", "100");
final Result rs2 = new Result (2, 1001, "Name 02", "Candidate01", "100");
final Result rs3 = new Result (3, 1002, "Name 03", "Candidate02", "150");
final Result rs4 = new Result (4, 1003, "Name 04", "Candidate03", "200");
final Result rs5 = new Result (5, 1004, "Name 05", null, null);

我想使用 Java 8 流功能来实现相同的目的。有人可以帮我吗?

我的班级详情

public class Candidate {
    private int canId;
    private String candidateName;
    private String score;
    //Getter setter with constructors.
}

public class Org{
    private int id;
    private int canId;
    private String name;
    //Getter setter with constructors
}

public class Result {
    private int id;
    private int canId;
    private String name;
    private String candidateName;
    private String score;   
    //Getter setter with constructors.
}

Org 类有一个canId,作为CandidateClass 的映射点。

标签: javacollectionsjava-8java-stream

解决方案


你可以这样做,

Map<Integer, Candidate> candidateById = listCandidate.stream()
        .collect(Collectors.toMap(Candidate::getId, Function.identity()));
List<Result> resultList = listOrg.stream()
        .map(o -> {
          Candidate candidate = candidateById.getOrDefault(o.getCandidateId(), new Candidate(-1, null, null));
          return new Result(o.getId(), o.getCandidateId(), o.getName(), candidate.getName(), candidate.getNum());
    })
    .collect(Collectors.toList());

Map首先根据Candidate它们的 Id 值创建一个对象。然后遍历对象,从给定 Id 值的映射ListOrg获取关联的Candidate实例,并将它们合并在一起形成一个Result. 最后把所有的收集Results成一个List

更新

根据下面的评论,这可以进一步改进,

List<Result> resultList = listOrg.stream()
        .map(o -> new Result(o, candidateById.get(o.getCandidateId())))
        .collect(Collectors.toList());

构造Result函数现在看起来像这样,

public Result(Org org, Candidate candidate) {
        super();
        this.orgId = org.getId();
        this.candidateId = org.getCandidateId();
        this.orgName = org.getName();
        this.candidateName = Optional.ofNullable(candidate).map(c -> c.getName()).orElse(null);
        this.candidateNum = Optional.ofNullable(candidate).map(c -> c.getNum()).orElse(null);
    }

推荐阅读