HashMap的值是没有顺序的,它是按照key的HashCode来实现的。对于这个无序的HashMap我们要怎么来实现排序呢?(TreeMap类似)
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; Mapmap = new HashMap (); map.put("c", 33333L); map.put("a", 11111L); map.put("d", 44444L); map.put("e", 55555L); map.put("b", 22222L); //将map.entrySet()转换成list List > list = new ArrayList >(map.entrySet()); Collections.sort(list, new Comparator >() { //降序排序 @Override public int compare(Entry o1, Entry o2) { //return o1.getValue().compareTo(o2.getValue()); return o2.getValue().compareTo(o1.getValue()); } }); String clientId = "4,5,6,7,8,9,0,1,a,c,e"; reportClientIds = clientId.split(","); for (Map.Entry mapping : list) { if (Arrays.asList(reportClientIds).contains(mapping.getKey())) { ClientIds.add(mapping.getKey()); } System.out.println(mapping.getKey() + ":" + mapping.getValue()); }
e:55555 d:44444 c:33333 b:22222 a:11111