1.数据加入到Map中,因为每一条数据都是entry,因此我们可以TreeSet存储,然后重写compare()或者compareTo()方法实现
代码:
Sutdent 类 implements Comparable
{
①构造器;
②Getter() Setter() 方法;
③ 重写equals 和hashCode()方法
@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Students)) return false; Students students = (Students) o; if (!name.equals(students.name)) return false; return score.equals(students.score); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + score.hashCode(); return result; }
}
Ⅰ在Student类中重写compareTo(Object o)方法
代码:
@Override public int compareTo(Object o) { if (o instanceof Students){ return -this.score.compareTo(((Students) o).score); }else return 0; }
@Test public void AboutMap(){ Map map = new HashMap(); map.put("AA",85); map.put("AB",38); map.put("BB",98); map.put("CC",48); map.put("DD",57); map.put("FF",25); Set set1 = map.keySet(); TreeSet set = new TreeSet(); for (Object object :set1) { // System.out.println(object+"---"+map.get(object)); set.add(new Students((String) object,(int)map.get(object))); } System.out.println(""); int i=0; for (Object obj: set) { if(i<3) { // System.out.println("**"+obj.toString()); Students students = (Students) obj; System.out.println(students.getName()); } i++; } }
Ⅱ在类中匿名类 实现重写compare(Object o1,Object o2)
代码:
@Test
public void AboutMap1(){
Map map = new HashMap();
map.put("AA",85);
map.put("AB",38);
map.put("BB",98);
map.put("CC",48);
map.put("DD",57);
map.put("FF",25);
Set set1 = map.keySet();Map
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof Students && o2 instanceof Students ){
Students s1 = (Students) o1;
Students s2 = (Students) o2;
int i =s1.getScore().compareTo(s2.getScore());
/* if(i==1){ //定制排序,根据成绩和姓名,若成绩相等按照姓名的大小排
return s1.getName().compareTo(s2.getName());
}*/
return -i;
}
return 0;
}
};
TreeSet set = new TreeSet(comparator);
for (Object object :set1) {
set.add(new Students((String) object,(int)map.get(object)));
}
int j=0;
for (Object o: set) {
if(j<3) {
Students s = (Students) o;
System.out.println(s.getName());
}
j++;
}
System.out.println(set);
}