场景:需要把考生进行分类处理。已知考生在一个List容器中。考生有所属机构。


分析:如何才能把List中的考生分类呢?有考生id,有机构id,有机构名称,而且我应该按照机构id进行分类。


思考:按照什么进行分类处理?考生所属机构。建立一个CandidateOrg类,类中拥有orgId,orgName,candidateIdList。


如何存储:一个CandidateOrg对象是一个组织机构,这个组织机构中拥有一个List属性,而这个candidateIdList属性,就保存当前机构下的所有考生id。


需要的类:Candidate,CandidateOrg。


public class Candidate{
private String orgId;//我的目的是以这个orgId分类
private String orgName;
private String candidateId;

public Candidate(){

}

public Candidate(String orgId, String candidateId, String orgName) {
super();
this.candidateId = candidateId;
this.orgId = orgId;
this.orgName = orgName;
}


public String getCandidateId() {
return candidateId;
}

public void setCandidateId(String candidateId) {
this.candidateId = candidateId;
}

public String getOrgId() {
return orgId;
}

public void setOrgId(String orgId) {
this.orgId = orgId;
}

public String getOrgName() {
return orgName;
}

public void setOrgName(String orgName) {
this.orgName = orgName;

}

}


public class CandidateOrg{
private String orgId;
private String orgName;
private List<String> candidateIdList;

public CandidateOrg() {

}

public CandidateOrg(String orgId, String orgName, List<String> candidateIdList) {
super();
this.orgId = orgId;
this.orgName = orgName;
this.candidateIdList = candidateIdList;
}

public String getOrgId() {
return orgId;
}

public void setOrgId(String orgId) {
this.orgId = orgId;
}

public String getOrgName() {
return orgName;
}

public void setOrgName(String orgName) {
this.orgName = orgName;
}

public List<String> getCandidateIdList() {
return candidateIdList;
}

public void setCandidateIdList(List<String> candidateIdList) {
this.candidateIdList = candidateIdList;

}

}


public class TestCandidateOrg {
public static void main(String[] args) {
List<Candidate> list = new ArrayList<Candidate>();
list.add(new Candidate("1","1","机构一"));//机构id,考生id,机构名称。
list.add(new Candidate("1","2","机构一"));
list.add(new Candidate("2","3","机构二"));
list.add(new Candidate("2","4","机构二"));

List<CandidateOrg> CandidateOrgList = new ArrayList<CandidateOrg>();
for (Candidate can : list) {
CandidateOrg canExist = null;
boolean bFound = false;
for (CandidateOrg candidateOrg : CandidateOrgList) {
if (candidateOrg.getOrgId().equals(can.getOrgId())) {
canExist = candidateOrg;
canExist.getCandidateIdList().add(can.getCandidateId());
bFound = true;
break;
}
}
if (!bFound) {
canExist = new CandidateOrg();//如果没有找到就创建一个
canExist.setOrgId(can.getOrgId());
canExist.setOrgName(can.getOrgName());
List<String> candidateIdList = new ArrayList<String>();
canExist.setCandidateIdList(candidateIdList);
canExist.getCandidateIdList().add(can.getCandidateId());
}
if (!bFound) {
CandidateOrgList.add(canExist);
}
}
}

}


实现项目中的一个应用:




Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐