TreeMap相关用法

2019-02-24  本文已影响0人  夜阑w

TreeMap类通过使用树来实现Map接口。TreeMap提供了按排序顺序存储关键字/值对的有效手段,同时允许快速检索。不像散列映射,树映射保证它的元素按照关键字升序排序。

对key按升序排序:

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<String, Integer> map = new TreeMap<>();//(new DeComparator());
        map.put("A", 1);
        map.put("a", 2);
        map.put("B", 3);
        Set<String> keys = map.keySet();
        Iterator<String> iter = keys.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(" " + key + ":" + map.get(key));
        }
    }
}

输出结果:

 A:1
 B:3
 a:2

如果要改变其排序可以自己写一个Comparator,例如将其改为降序:

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<String, Integer> map = new TreeMap<>(new DeComparator());
        map.put("A", 1);
        map.put("a", 2);
        map.put("B", 3);
        Set<String> keys = map.keySet();
        Iterator<String> iter = keys.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(" " + key + ":" + map.get(key));
        }
    }
}

import java.util.Comparator;

class DeComparator implements Comparator {
    public int compare(Object o1, Object o2) {
        String i1 = (String) o1;
        String i2 = (String) o2;
        return -i1.compareTo(i2);
    }
}

输出结果:

 a:2
 B:3
 A:1
上一篇 下一篇

猜你喜欢

热点阅读