package com.oracle.collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class Map_Student {
public static void main(String[] args) {
Comparator com=new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
int i=s2.getGrade().compareTo(s1.getGrade());
return i;
}
};
Map map=new HashMap();
map.put("1",new Student("lxg",94));
map.put("2",new Student("zy",98));
map.put("3",new Student("lr",89));
map.put("4",new Student("wq",88));
Set set=map.entrySet();
Iterator it=set.iterator();
TreeSet ts=new TreeSet(com);
while(it.hasNext()){
Map.Entry m=(Map.Entry)it.next();
ts.add(m.getValue());
System.out.println(m.getValue().toString());
}
System.out.println();
Iterator its=ts.iterator();
int i=0;
while (its.hasNext()){
if(i==3)
break;
System.out.println(its.next());
i++;
}
}
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class Map_Student {
public static void main(String[] args) {
Comparator com=new Comparator(){
@Override
public int compare(Object o1, Object o2) {
Student s1=(Student)o1;
Student s2=(Student)o2;
int i=s2.getGrade().compareTo(s1.getGrade());
return i;
}
};
Map map=new HashMap();
map.put("1",new Student("lxg",94));
map.put("2",new Student("zy",98));
map.put("3",new Student("lr",89));
map.put("4",new Student("wq",88));
Set set=map.entrySet();
Iterator it=set.iterator();
TreeSet ts=new TreeSet(com);
while(it.hasNext()){
Map.Entry m=(Map.Entry)it.next();
ts.add(m.getValue());
System.out.println(m.getValue().toString());
}
System.out.println();
Iterator its=ts.iterator();
int i=0;
while (its.hasNext()){
if(i==3)
break;
System.out.println(its.next());
i++;
}
}
}
其中student为map中value值:
package com.oracle.collection;
public class Student implements Comparable {
private String name;
private int grade;
public Student(String name,int garde){
this.name=name;
this.grade=garde;
}
@Override
public String toString() {
return "Student [name=" + name + ", grade=" + grade + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}