两个不同的list 有相同的 主键 快速 融合
package java2015.java07.java; import java.util.ArrayList; import java.util.List; /** * @author baoyou E-mail:curiousby@163.com * @version 创建时间:2015年7月8日 下午4:06:41 * 类说明: */ public class Test { static List<Student> slist = new ArrayList<Student>(); static List<ClazzStudentRelation> clist = new ArrayList<ClazzStudentRelation>(); static { for (int i = 1; i <= 5; i++) { slist.add( new Student(i+"", i+"") ); } for (int i = 1; i <= 2; i++) { clist.add(new ClazzStudentRelation(i+"", i+"") ); } } public static void main(String[] args) { List<StudentVO> svolist = new ArrayList<StudentVO>(); for (int i = 0; i < slist.size(); i++) { Student st = slist.get(i); StudentVO stvo = new StudentVO(st); if (clist.contains(new ClazzStudentRelation(st.getId()))) { stvo.setClazzId(getClazzStudentRelation(clist, st.getId()).getClazzId()); } svolist.add(stvo); } for (int i = 0; i < svolist.size(); i++) { System.out.println(svolist.get(i)); } } private static ClazzStudentRelation getClazzStudentRelation(List<ClazzStudentRelation> clist , String id){ for (int i = 0; i < clist.size(); i++) { ClazzStudentRelation csr = clist.get(i); if ( id .equals(csr.getUserid()) ) { return csr; } } return null; } } class Student { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(){} public Student(String id, String name) { this.id = id; this.name = name; } } class ClazzStudentRelation{ private String userid; private String clazzId; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getClazzId() { return clazzId; } public void setClazzId(String clazzId) { this.clazzId = clazzId; } public ClazzStudentRelation(){} public ClazzStudentRelation(String userid ) { this.userid = userid; } public ClazzStudentRelation(String userid, String clazzId) { this.userid = userid; this.clazzId = clazzId; } @Override public boolean equals(Object obj) { if (obj != null) if (obj instanceof ClazzStudentRelation) return this.userid .equals(((ClazzStudentRelation) obj).getUserid()); return false; } } class StudentVO extends Student{ StudentVO(Student student ){ setId(student.getId()); setName(student.getName()); } private String clazzId; public String getClazzId() { return clazzId; } public void setClazzId(String clazzId) { this.clazzId = clazzId; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append (getClass().getName().substring(getClass().getName().lastIndexOf(".")+1, getClass().getName().length())); sb.append(":["); sb.append("\"id\":\"" +getId()+"\"," ); sb.append("\"name\":\"" +getName()+"\"," ); sb.append("\"clazzId\":\"" +clazzId+"\"" ); sb.append("]"); return sb.toString() ; } }
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!