Home > Java > javaTutorial > Can map in java be sorted by key?

Can map in java be sorted by key?

青灯夜游
Release: 2019-12-31 15:59:52
Original
3374 people have browsed it

Can map in java be sorted by key?

Can map be sorted by key?

Map can be sorted by key. Let’s take a look at an example below.

Example: Java Map sorting by Key and sorting by 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;
    }
}
Copy after login

java map

Map is a collection interface of key-value pairs, and its implementation The classes mainly include: HashMap, TreeMap, Hashtable and LinkedHashMap, etc.

Map does not allow duplicate keys, but allows duplicate values.

1. HashMap:

The most commonly used Map stores data according to the hashcode value of the key. Its value can be obtained directly according to the key (because the same key has the same hashcode value, and the address is The hashcode value stores the value, so the value can be obtained directly according to the key), which has a very fast access speed. When traversing, the order of obtaining data is completely random. HashMap only allows the key of one record to be null at most, and allows multiple The value of the record is null. HashMap does not support thread synchronization, that is, multiple threads can write HashMap at the same time at any time, which will cause data inconsistency. If synchronization is needed, you can use the synchronziedMap method to make HashMap synchronized or use concurrentHashMap

2. HashTable:

Similar to HashMap, the difference is that it does not allow the recorded keys or values ​​to be empty, and supports thread synchronization, that is, only one thread can write to the HashTable at any time, so It also causes HashTable to be slower when writing!

3. LinkedHashMap:

is a subclass of HahsMap, but it maintains the insertion order of records. When traversing, the one obtained first must be the first. Inserted, you can also take parameters during construction and sort by the number of applications. The traversal will be slower than HahsMap, but there is an exception. When the capacity of HashMap is large and the actual data is small, the traversal will be slower than LinkedHashMap (because it is Chain), because the traversal speed of HashMap is related to its capacity, and the traversal speed of LinkedHashMap is only related to the amount of data

4. TreeMap:

implements the sortMap interface, which can sort the saved records according to the key Sorting (default ascending order), you can also specify a sorting comparator, the data obtained during traversal is sorted

Recommended learning: Java video tutorial

The above is the detailed content of Can map in java be sorted by key?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template