import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
class User {
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "name:"+name+" age:"+age;
}
}
public class ListDemo {
public static void main(String[] args) {
HashMap<Integer, User> map = new HashMap<Integer, User>();
map.put(1, new User("jack", 20));
map.put(2, new User("jery", 32));
map.put(3, new User("jack", 17));
map.put(4, new User("jack", 12));
map.put(5, new User("jack", 28));
LinkedList<Entry<Integer, User>> list = new LinkedList<>(map.entrySet());
Collections.sort(list ,new Comparator<Entry<Integer, User>>() {
@Override
public int compare(Entry<Integer, User> o1, Entry<Integer, User> o2) {
return o2.getValue().age - o1.getValue().age;
}
});</span>
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getValue().toString());
}
}
}
java Map對象排序demo
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.