Java實現List中的資料分類
場景:需要把考生進行分類處理。已知考生在一個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
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);
}
}
}
}
實現專案中的一個應用: