Java 中TreeMap实现详细代码

SortedMap接口主要提供有序的Map实现。

Map的主要实现有HashMap,TreeMap,HashTable,LinkedHashMap。

TreeMap实现了SortedMap接口,保证了有序性。默认的排序是根据key值进行升序排序,也可以重写comparator方法来根据value进行排序。

HashMap与TreeMap的比较

public class SortedMapTest2 {
    
    public static void main(String[] args) {
        
        Map<String,Object> hashMap = new HashMap<String,Object>();
        hashMap.put("1", "a");
        hashMap.put("5", "b");
        hashMap.put("2", "c");
        hashMap.put("4", "d");
        hashMap.put("3", "e");
        Set<Entry<String, Object>> entry = hashMap.entrySet();
        for(Entry<String, Object> temp : entry){
            System.out.println("hashMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
        
        System.out.println("\n");  
        
        SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
        sortedMap.put("1", "a");
        sortedMap.put("5", "b");
        sortedMap.put("2", "c");
        sortedMap.put("4", "d");
        sortedMap.put("3", "e");
        Set<Entry<String, Object>> entry2 = sortedMap.entrySet();
        for(Entry<String, Object> temp : entry2){
            System.out.println("sortedMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
        
    }
 
}
运算的结果为

hashMap:1 值a
hashMap:2 值c
hashMap:3 值e
hashMap:4 值d
hashMap:5 值b
 
sortedMap:1 值a
sortedMap:2 值c
sortedMap:3 值e
sortedMap:4 值d
sortedMap:5 值b
看上去还以为HashMap也保证了有序性,其实是随机的,如果值设置的复杂一点,如下例:

public class SortedMapTest3 {
    
    public static void main(String[] args) {
        
        Map<String,Object> hashMap = new HashMap<String,Object>();
        hashMap.put("1b", "a");
        hashMap.put("2", "b");
        hashMap.put("4b", "d");
        hashMap.put("3", "c");
        hashMap.put("2b", "d");
        hashMap.put("3b", "c");
        Set<Entry<String, Object>> entry = hashMap.entrySet();
        for(Entry<String, Object> temp : entry){
            System.out.println("hashMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
        
        System.out.println("\n");  
        
        SortedMap<String,Object> sortedMap = new TreeMap<String,Object>();
        sortedMap.put("1b", "a");
        sortedMap.put("2", "b");
        sortedMap.put("4b", "d");
        sortedMap.put("3", "c");
        sortedMap.put("2b", "d");
        sortedMap.put("3b", "c");
        Set<Entry<String, Object>> entry2 = sortedMap.entrySet();
        for(Entry<String, Object> temp : entry2){
            System.out.println("sortedMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
        
    }
 
}
运算的结果是:

hashMap:2b 值d
hashMap:1b 值a
hashMap:2 值b
hashMap:3 值c
hashMap:4b 值d
hashMap:3b 值c
 
sortedMap:1b 值a
sortedMap:2 值b
sortedMap:2b 值d
sortedMap:3 值c
sortedMap:3b 值c
sortedMap:4b 值d
很显然只有TreeMap保证了有序性。

那如果想要根据value值来进行排序

public class SortedMapTest {
    
    public static void main(String[] args) {
        
        SortedMap<String,String> sortedMap = new TreeMap<String,String>();
        sortedMap.put("1", "a");
        sortedMap.put("5", "b");
        sortedMap.put("2", "c");
        sortedMap.put("4", "d");
        sortedMap.put("3", "e");
        Set<Entry<String, String>> entry2 = sortedMap.entrySet();
        for(Entry<String, String> temp : entry2){
            System.out.println("修改前 :sortedMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
        System.out.println("\n");  
        
        //这里将map.entrySet()转换成list
        List<Map.Entry<String,String>> list = 
                new ArrayList<Map.Entry<String,String>>(entry2);
        
        Collections.sort(list, new Comparator<Map.Entry<String,String>>(){
 
            @Override
            public int compare(Entry<String, String> o1, Entry<String, String> o2) {
                // TODO Auto-generated method stub
                return o1.getValue().compareTo(o2.getValue());
            }
            
        });
        
        for(Map.Entry<String,String> temp :list){
            System.out.println("修改后 :sortedMap:"+temp.getKey()+" 值"+temp.getValue());  
        }
    }
 
}
运行结果为:

修改前 :sortedMap:1 值a
修改前 :sortedMap:2 值c
修改前 :sortedMap:3 值e
修改前 :sortedMap:4 值d
修改前 :sortedMap:5 值b
 
修改后 :sortedMap:1 值a
修改后 :sortedMap:5 值b
修改后 :sortedMap:2 值c
修改后 :sortedMap:4 值d
修改后 :sortedMap:3 值e

Java TreeMap可以按照value排序,可以通过实现Comparator接口来实现。具体步骤如下: 1. 创建一个实现Comparator接口的类,重写compare方法,比较两个value的大小。 2. 创建一个TreeMap对象,并将实现了Comparator接口的类作为参数传入。 3. 将需要排序的键值对添加到TreeMap。 4. 使用entrySet()方法获取TreeMap的所有键值对,并将其转换为List。 5. 使用Collections.sort()方法对List进行排序。 6. 遍历排序后的List,输出键值对。 示例代码如下: ``` import java.util.*; public class TreeMapSortByValue { public static void main(String[] args) { // 创建一个实现Comparator接口的类 ValueComparator vc = new ValueComparator(); // 创建一个TreeMap对象,并将实现了Comparator接口的类作为参数传入 TreeMap<String, Integer> map = new TreeMap<>(vc); // 将需要排序的键值对添加到TreeMap map.put("apple", 10); map.put("banana", 5); map.put("orange", 8); // 使用entrySet()方法获取TreeMap的所有键值对,并将其转换为List List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet()); // 使用Collections.sort()方法对List进行排序 Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o1.getValue().compareTo(o2.getValue()); } }); // 遍历排序后的List,输出键值对 for (Map.Entry<String, Integer> entry : list) { System.out.println(entry.getKey() + " : " + entry.getValue()); } } } // 实现Comparator接口的类 class ValueComparator implements Comparator<String> { Map<String, Integer> map = new HashMap<>(); public ValueComparator() {} public ValueComparator(Map<String, Integer> map) { this.map.putAll(map); } @Override public int compare(String s1, String s2) { if (map.get(s1) >= map.get(s2)) { return 1; } else { return -1; } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值