1、默认按key排序
//treeMap
private static void test01(){
TreeMap<String, Object> treeMap = new TreeMap<String, Object>();
treeMap.put("zs", 15);
treeMap.put("ls",18);
treeMap.put("ww", 22);
String key = treeMap.firstEntry().getKey();
String key2 = treeMap.lastEntry().getKey();
System.out.println(key);
System.out.println(key2);
}
2、treeMap按值排序
private static void test02(){
TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
treeMap.put("zs", 18);
treeMap.put("ls",25);
treeMap.put("ww", 22);
Set<Entry<String,Integer>> entrySet = treeMap.entrySet();
List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(entrySet);
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> entry1, Entry<String, Integer> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
});
for(Entry<String, Integer> entry : list) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
往期精彩内容:
Java知识体系总结
Spring框架总结
超详细的springBoot学习笔记
常见数据结构与算法整理总结
Java设计模式:23种设计模式全面解析
Java面试题总结(附答案)
Linux知识体系总结
Redis知识体系总结
相关文章
暂无评论...