1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package jcf;
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import java.util.Set;
public class HashMapTest { public static HashMap<Integer,User> sortHashMap(HashMap<Integer,User> users){ Set<Entry<Integer,User>> usersEntrySet = users.entrySet(); ArrayList<Entry<Integer,User>> usersList = new ArrayList<>(usersEntrySet); Collections.sort(usersList, new Comparator<Entry<Integer,User>>() {
@Override public int compare(Entry<Integer,User> o1, Entry<Integer,User> o2) {
return o2.getValue().getAge() - o1.getValue().getAge(); } }); LinkedHashMap<Integer, User> usersLinkHashMap = new LinkedHashMap<>(); for (Entry<Integer, User> entry : usersList) { usersLinkHashMap.put(entry.getKey(), entry.getValue()); } return usersLinkHashMap; } public static void main(String[] args) { HashMap<Integer,User> users = new HashMap<>(); users.put(1, new User("张三",25)); users.put(2, new User("李四",28)); users.put(3, new User("王五",23)); HashMap<Integer, User> sortHashMap = sortHashMap(users); System.out.println(sortHashMap); } }
|