@Test
public void testMapSort() {
Map<String, String> map = new HashMap<>();
map.put("bdc", "bbb");
map.put("caf", "ccc");
map.put("aef", "aaa");
map.put("def", "ddd");
System.out.println("排序前:" + map);
//进行排序
List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> 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