@Test
public void testMapSort() {
Mapmap = new HashMap<>();
map.put("bdc", "bbb");
map.put("caf", "ccc");
map.put("aef", "aaa");
map.put("def", "ddd");
System.out.println("排序前:" + map);
//进行排序
List> entries = new ArrayList >(map.entrySet());
Collections.sort(entries, new Comparator>() {
@Override
public int compare(Map.Entryo1, Map.Entry o2) {
return o1.getKey().compareTo(o2.getKey());
}
});
System.out.println("排序后:" + entries);
//将key,value拼接
StringBuffer sb = new StringBuffer();
entries.forEach(x -> sb.append(x.getKey()).append(x.getValue()));
System.out.println("拼接后结果:" + sb.toString());
}
控制台输出结果:
排序前:{bdc=bbb, aef=aaa, def=ddd, caf=ccc}
排序后:[aef=aaa, bdc=bbb, caf=ccc, def=ddd]
拼接后结果:aefaaabdcbbbcafcccdefddd