Last active
May 26, 2016 06:38
-
-
Save KingSirLee/80883dbb527ea1e43f7e858d1143756c to your computer and use it in GitHub Desktop.
有两个对象a和b,两个集合,他们中储存了,很多条学生的信息,但是a和b中的学生信息由重复的(比如sno 相同),现在要求通过contains()方法,来把a和b合并为一个list对象,并且,要去掉重复的学生信息,并且在list中存储的学生信息要按照学号升序存储。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.LinkedList; | |
import java.util.List; | |
public class Student{ | |
String sno; | |
String sname; | |
public Student (String sno, String sname){ | |
this.sno = sno; | |
this.sname = sname; | |
} | |
public String getSno (){ | |
return sno; | |
} | |
public void setSno (String sno){ | |
this.sno = sno; | |
} | |
public String getSname (){ | |
return sname; | |
} | |
public void setSname (String sname){ | |
this.sname = sname; | |
} | |
@Override | |
public String toString (){ | |
StringBuilder builder = new StringBuilder (); | |
builder.append ("Student [sno=").append (sno).append (", sname=").append (sname).append ("]"); | |
return builder.toString (); | |
} | |
private static List<Student> contains ( List<Student> a, List<Student> b ){ | |
List<Student> list = new LinkedList<Student>(); | |
list.addAll (a); | |
String temp = list.toString (); | |
for (Student student : b){ | |
String reg = "sno=" + student.getSno () + ","; | |
if (temp.indexOf (reg) == -1){ | |
list.add (student); | |
} | |
} | |
Collections.sort (list, new Comparator<Student> (){ | |
@Override | |
public int compare (Student o1, Student o2){ | |
int a = Integer.parseInt (o1.getSno ()); | |
int b = Integer.parseInt (o2.getSno ()); | |
if (a > b){ | |
return 1; | |
} else if (a < b){ | |
return -1; | |
} else { | |
return 0; | |
} | |
} | |
}); | |
return list; | |
} | |
public static void main ( String[] args ){ | |
Student s1 = new Student ("100", "ko"); | |
Student s2 = new Student ("102", "pi"); | |
Student s3 = new Student ("101", "pid"); | |
Student s4 = new Student ("102", "pi"); | |
List<Student> a = Arrays.asList (s1, s2); | |
List<Student> b = Arrays.asList (s3, s4); | |
List<Student> c = contains (a, b); | |
for ( Student student : c ){ | |
System.out.println (student); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment