欢迎光临
我们一直在努力

java中map可以按key排序吗?

map可以按key排序吗?

map可以按key排序,下面通过实例来看看。

示例:Java Map 按Key排序和按Value排序

package test;  import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.Map.Entry;  public class MapSortDemo {      /**      * @param args      */     public static void main(String[] args) {         Map<String, String> hMap = new HashMap<String, String>();         hMap.put("a", "3");         hMap.put("z", "2");         hMap.put("b", "6");         hMap.put("o", "9");          System.out.println("根据key升序排序");          Map<String, String> sortByKeyResultMap = sortMapByKey(hMap);    //按Key进行排序         Iterator<Map.Entry<String, String>> sortByKeyEntries = sortByKeyResultMap.entrySet().iterator();          while (sortByKeyEntries.hasNext()) {            Map.Entry<String, String> entry = sortByKeyEntries.next();            System.out.println("Key = " + entry.getKey() + "------->Value = " + entry.getValue());          }                  System.out.println("------------------------------");                   System.out.println("根据value降序排序");          Map<String, String> sortByValueResultMap = sortMapByValue(hMap); //按Value进行排序         Iterator<Map.Entry<String, String>> sortByValueEntries = sortByValueResultMap.entrySet().iterator();          while (sortByValueEntries.hasNext()) {            Map.Entry<String, String> entry = sortByValueEntries.next();            System.out.println("Key = " + entry.getKey() + "------->Value = " + entry.getValue());          }     }     /**      * 使用 Map按key进行排序      * @param map      * @return      */     public static Map<String, String> sortMapByKey(Map<String, String> map) {         if (map == null || map.isEmpty()) {             return null;         } //        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());         Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {             public int compare(String obj1, String obj2) {                 return obj1.compareTo(obj2);//升序排序             }         });         sortMap.putAll(map);         return sortMap;     }          /**      * 使用 Map按value进行排序      * @param map      * @return      */     public static Map<String, String> sortMapByValue(Map<String, String> map) {         if (map == null || map.isEmpty()) {             return null;         }         Map<String, String> sortedMap = new LinkedHashMap<String, String>();         List<Map.Entry<String, String>> entryList = new ArrayList<Map.Entry<String, String>>(map.entrySet()); //        Collections.sort(entryList, new MapValueComparator());         Collections.sort(             entryList,              new Comparator<Map.Entry<String, String>>(){                    public int compare(Entry<String, String> o1, Entry<String, String> o2) {                        return o2.getValue().compareTo(o1.getValue());// 降序排序                    }             }         );          Iterator<Map.Entry<String, String>> iter = entryList.iterator();         Map.Entry<String, String> tmpEntry = null;         while (iter.hasNext()) {             tmpEntry = iter.next();             sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue());         }         return sortedMap;     } }

java map

Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等。

Map不允许键(key)重复,但允许值(Value)重复。

1、HashMap:

最常用的Map,根据键的hashcode值来存储数据,根据键可以直接获得他的值(因为相同的键hashcode值相同,在地址为hashcode值的地方存储的就是值,所以根据键可以直接获得值),具有很快的访问速度,遍历时,取得数据的顺序完全是随机的,HashMap最多只允许一条记录的键为null,允许多条记录的值为null,HashMap不支持线程同步,即任意时刻可以有多个线程同时写HashMap,这样对导致数据不一致,如果需要同步,可以使用synchronziedMap的方法使得HashMap具有同步的能力或者使用concurrentHashMap

2、HashTable:

与HashMap类似,不同的是,它不允许记录的键或值为空,支持线程同步,即任意时刻只能有一个线程写HashTable,因此也导致HashTable在写入时比较慢!

3、LinkedHashMap:

是HahsMap的一个子类,但它保持了记录的插入顺序,遍历时先得到的肯定是先插入的,也可以在构造时带参数,按照应用次数排序,在遍历时会比HahsMap慢,不过有个例外,当HashMap的容量很大,实际数据少时,遍历起来会比LinkedHashMap慢(因为它是链啊),因为HashMap的遍历速度和它容量有关,LinkedHashMap遍历速度只与数据多少有关

4、TreeMap:

实现了sortMap接口,能够把保存的记录按照键排序(默认升序),也可以指定排序比较器,遍历时得到的数据是排过序的

推荐学习:Java视频教程

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。