public class CountString {
public static void main(String[] args) {
Map<String, Integer> maps = new HashMap<String, Integer>();
maps.put("abc",2);
maps.put("xyz",9);
maps.put("jpg",7);
List<Map.Entry<String, Integer>> entryLists = new ArrayList<Map.Entry<String, Integer>>(maps.entrySet());
Collections.sort(entryLists, new EntryComparator());
// System.out.println(entryLists);
for (Map.Entry<String, Integer> entry : entryLists) {
System.out.print(entry.getKey() + ":" + entry.getValue()+" ");
}
}
public static class EntryComparator implements Comparator<Map.Entry<String, Integer>> {// value列表顺序的比较器
public int compare(Map.Entry<String, Integer> map1, Map.Entry<String, Integer> map2) {// 重写compare方法
return map1.getValue() - map2.getValue(); // 升序排列
// return map2.getValue() - map1.getValue();// 降序排列
}
}
}
排序后,输出结果为:abc:2 xyz:7 jpg:9
本文提供了一个使用Java实现的字符串映射排序示例。通过自定义比较器对包含字符串及其对应整数值的映射进行排序,并将排序后的结果输出。该示例展示了如何利用集合框架中的Map和List以及自定义Comparator来完成这一任务。
373

被折叠的 条评论
为什么被折叠?



