主要map 先排序key后排序值
public static void main(String[] args) {
/**
* 建的排序
*/
Map<String, String> map = new TreeMap<String,String>();
map.put("11", "aa");
map.put("22", "bb");
map.put("99", "cc");
map.put("44", "dd");
map.put("55", "ee");
map.put("66", "ff");
for (Entry<String, String> entry : map.entrySet()){
System.out.println("key=" + entry.getKey() +"; value : " + entry.getValue());
}
//Map集合的排序
Map<String, Integer> valueCompare = new TreeMap<String, Integer>(new Comparator<String>() {//可以在这里设置key的排序需求
@Override
public int compare(String o1, String o2) {
int com = o1.compareTo(o2);
return com;
}
});
valueCompare.put("e", 9);
valueCompare.put("b", 3);
valueCompare.put("a", 10);
valueCompare.put("d", 9);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(valueCompare.entrySet());
System.out.println("-------------排序前--------------");
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
// 根据自己的需求排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {//
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return ( o1.getValue()-o2.getValue());
}
});
System.out.println("--------------排序后--------------");
for (int i = 0; i < infoIds.size(); i++) {
Entry<String,Integer> ent=infoIds.get(i);
System.out.println(ent.getKey()+"="+ent.getValue());
}
}
参考:2
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("lisi", 5);
map.put("lisi1", 1);
map.put("lisi2", 3);
map.put("lisi3", 9);
List<Map.Entry<String, Integer>> infoIds = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
System.out.println("--------------排序前--------------");
for (int i = 0; i < infoIds.size(); i++) {
String id = infoIds.get(i).toString();
System.out.println(id);
}
// 排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return ( o1.getValue()-o2.getValue());
}
});
System.out.println("--------------排序后--------------");
for (int i = 0; i < infoIds.size(); i++) {
Entry<String,Integer> ent=infoIds.get(i);
System.out.println(ent.getKey()+"="+ent.getValue());
}
}