Map 集合按字母排序方法

放肆的年华 提交于 2020-08-08 18:02:15
@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






























标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!