Java 根据键对HashMap进行排序

Java 根据键对HashMap进行排序

我们以HashMap的形式得到了学生的分数详情,其中学生的名字是键,分数是值。我们的任务是根据键值(即按字母顺序(lexicographical)排列的学生姓名)对该地图进行排序。

例子
输入 : Key = Jayant, Value = 80
Key = Anushka, Value = 80
Key = Amit, Value = 75
Key = Abhishek, Value = 90
Key = Danish, Value = 40
输出 : Sorted Map according to Names:
Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

建议。请先在{IDE}上尝试你的方法,然后再继续解决。

使用TreeMap (putAll方法)

我们的想法是将HashMap的所有数据放到一个TreeMap中。TreeMap遵循基于红黑树的实现。该地图根据其键的自然排序来进行排序。点击这里查看更多 …

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        // TreeMap to store values of HashMap
        TreeMap<String, Integer> sorted = new TreeMap<>();
 
        // Copy all data from hashMap into TreeMap
        sorted.putAll(map);
 
        // Display the TreeMap which is naturally sorted
        for (Map.Entry<String, Integer> entry : sorted.entrySet())
            System.out.println("Key = " + entry.getKey() +
                         ", Value = " + entry.getValue());       
    }
     
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
 
        // Calling the function to sortbyKey
        sortbykey();
    }
}

输出

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

注意: TreeMap为containsKey、get、put和remove操作提供了保证的 log(n) 时间成本。

使用TreeMap (构造函数)

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        // TreeMap to store values of HashMap
        TreeMap<String, Integer> sorted
            = new TreeMap<>(map);
 
        // Display the TreeMap which is naturally sorted
        for (Map.Entry<String, Integer> entry :
             sorted.entrySet())
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
 
        // Calling the function to sortbyKey
        sortbykey();
    }
}

输出

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

使用ArrayList

在这种方法中,我们使用ArrayList构造函数创建一个键的列表。然后,我们使用Collections.sort()方法对该列表进行排序。

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        ArrayList<String> sortedKeys
            = new ArrayList<String>(map.keySet());
 
        Collections.sort(sortedKeys);
 
        // Display the TreeMap which is naturally sorted
        for (String x : sortedKeys)
            System.out.println("Key = " + x
                               + ", Value = " + map.get(x));
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
 
        // Calling the function to sortbyKey
        sortbykey();
    }
}

输出

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

使用Java 8 Lambdas

这里我们将改变我们的排序方式,使用lambda表达式进行排序。逻辑是一样的,甚至我们也传递了比较器对象,但只是使用lambda。

下面是上述方法的实现。

// Java Code to sort Map by key value
import java.util.*;
class sortmapKey {
 
    // This map stores unsorted key
    static Map<String, Integer> map = new HashMap<>();
 
    // function to sort hashmap by keys
    public static Map<String, Integer>
    sortByKey(Map<String, Integer> hm)
    {
        // Create a list from elements of HashMap
        List<Map.Entry<String, Integer> > list
            = new LinkedList<Map.Entry<String, Integer> >(
                hm.entrySet());
 
        // Sort the list using lambda expression
        Collections.sort(
            list,
            (i1, i2) -> i1.getKey().compareTo(i2.getKey()));
 
        // put data from sorted list to hashmap
        HashMap<String, Integer> temp
            = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> aa : list) {
            temp.put(aa.getKey(), aa.getValue());
        }
        return temp;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
 
        // Calling the function to sortbyKey
        Map<String, Integer> hm1 = sortByKey(map);
 
        // print the sorted hashmap
        for (Map.Entry<String, Integer> en :
             hm1.entrySet()) {
            System.out.println("Key = " + en.getKey()
                               + ", Value = "
                               + en.getValue());
        }
    }
}

输出

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

使用Java 8流

这里我们将使用流来对地图进行排序。我们将使用 stream() 方法来获取entrySet的流,然后在sorted()方法中使用lambda表达式来对流进行排序,最后,我们将使用toMap() 方法将其转换成map。在toMap()方法中,我们使用 LinkedHashMap::new 方法引用来保留地图的排序顺序。

// Java Code to sort Map by key value
import static java.util.stream.Collectors.*;
 
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
class sortmapKey {
 
    // This map stores unsorted values
    static Map<String, Integer> map = new HashMap<>();
 
    // Function to sort map by Key
    public static void sortbykey()
    {
        HashMap<String, Integer> temp
            = map.entrySet()
                  .stream()
                  .sorted((i1, i2)
                              -> i1.getKey().compareTo(
                                  i2.getKey()))
                  .collect(Collectors.toMap(
                      Map.Entry::getKey,
                      Map.Entry::getValue,
                      (e1, e2) -> e1, LinkedHashMap::new));
 
        // Display the HashMap which is naturally sorted
        for (Map.Entry<String, Integer> entry :
             temp.entrySet()) {
            System.out.println("Key = " + entry.getKey()
                               + ", Value = "
                               + entry.getValue());
        }
    }
 
    // Driver Code
    public static void main(String args[])
    {
        // putting values in the Map
        map.put("Jayant", 80);
        map.put("Abhishek", 90);
        map.put("Anushka", 80);
        map.put("Amit", 75);
        map.put("Danish", 40);
 
        // Calling the function to sortbyKey
        sortbykey();
    }
}

输出

Key = Abhishek, Value = 90
Key = Amit, Value = 75
Key = Anushka, Value = 80
Key = Danish, Value = 40
Key = Jayant, Value = 80

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程