在 Java 中排序HashMap

原文:https://www.studytonight.com/java-examples/sorting-a-hashmap-in-java

Java 中的 HashMap 类用于存储键值对的集合。实现映射界面。HashMap 不按排序顺序存储键值对,也不维护元素的插入顺序。

然而,有时我们希望以排序的方式查看存储的数据。我们可以根据键或值对HashMap进行排序。

在本教程中,我们将学习如何对HashMap进行排序。

使用集合对HashMap进行排序

Collections 框架提供了一种方便的 sort()方法来对元素进行排序。我们可以将HashMap中的键或值复制到ArrayList中,然后,我们可以使用 Collections.sort()方法轻松地对它们进行排序。

按关键字排序

我们可以通过使用 keySet()方法获得HashMap中存在的键。我们可以将这个键集传递给ArrayList构造器。这将使用HashMap键初始化ArrayList。接下来,我们将简单地使用 sort()方法并打印排序后的键和相应的值。

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }
        //Creating an ArrayList with the HashMap keys
        ArrayList<String> sortedList = new ArrayList<>(unsortedMap.keySet());
        Collections.sort(sortedList);//Sorting the ArrayList

        System.out.println("\nPrinting the Alphabetically Sorted Keys");
        for(String s : sortedList)
        {
            System.out.println(s + "-->" + unsortedMap.get(s));
        }
    }
}

打印未排序的HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印按字母顺序排序的键 五- > 5 四- > 4 一- > 1 三- > 3 二- > 2

按值排序

同样,方法也是一样的。我们将首先使用 values()方法用 HashMap 值初始化一个ArrayList。然后,我们可以使用 sort()方法对它们进行排序。我们将无法看到排序值的对应键。给定一个值,没有办法从 HashMap 中获取键。

package snippet;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }
        //Creating an ArrayList with HashMap values
        ArrayList<Integer> sortedList = new ArrayList<>(unsortedMap.values());
        Collections.sort(sortedList);//Sorting the ArrayList

        System.out.println("\nPrinting the Sorted Values");
        for(Integer i : sortedList)
        {
            System.out.println(i);
        }
    }
}

打印未排序HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印排序值 1 2 3 4 5

利用TreeMapHashMap进行排序

如果您经常想查看按关键字排序的HashMap,那么TreeMap将是比HashMap更好的选择。TreeMap自动按排序顺序存储键值对(按键排序)。我们可以将 HashMap 中的所有数据复制到一个 TreeMap 中,数据将被排序。我们可以使用 putAll()方法,也可以将 HashMap 传递给 TreeMap 构造器。

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        TreeMap<String, Integer> sortedMap = new TreeMap<>(unsortedMap);//Passing HashMap object to TreeMap constructor
        //We can also use sortedMap.putAll(unsortedMap); 

        System.out.println("\nPrinting the Sorted TreeMap");
        for(Entry<String, Integer> e : sortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }    
    }
}

打印未排序的HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印已排序的TreeMap 五- > 5 四- > 4 一- > 1 三- > 3 二- > 2

使用TreeSet按值对HashMap进行排序

HashMap必须包含唯一的键,但是对值没有限制。它可以包含重复的值。如果我们只想考虑一次重复的值,我们可以在 TreeSet 的帮助下按键对HashMap进行排序。就像 TreeMap 一样,TreeSet 也按排序顺序存储数据。我们需要将值从映射复制到集合中,就这样。

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeSet;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        //Adding Duplicate Values
        unsortedMap.put("fourteen", 4);
        unsortedMap.put("fifteen", 5);
        unsortedMap.put("twenty", 2);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }
        //Creating a TreeSet using the HashMap values
        TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());

        System.out.println("\nThe sorted values are: " + sortedSet);
    }
}

打印未排序的 HashMap 十五- > 5 四- > 4 一- > 1 二- > 2 三- > 3 五- > 5 十四- > 4 二十- > 2

排序后的值为:【1,2,3,4,5】

使用流和 Lambda 表达式对HashMap进行排序

我们可以使用 Java Streams 和 Lambda 表达式在一行代码中对 HashMap 进行排序。我们将使用对键值条目流调用 sorted()对象。

按关键字排序

我们将使用 comparingByKey Comparator和 sorted()方法按关键字对映射进行排序。

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        Stream sortedStream = unsortedMap.entrySet()
                                         .stream()
                                         .sorted(Map.Entry.<String, Integer>comparingByKey());
        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);

    }
}

打印未排序的HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印已排序的键值对 五=5 四=4 一=1 三=3 二=2

按值排序

我们将使用 comparingByValue Comparator根据值对 HashMap 进行排序。

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        Stream sortedStream = unsortedMap.entrySet()
                                         .stream()
                                         .sorted(Map.Entry.<String, Integer>comparingByValue());
        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);

    }
}

打印未排序的HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印已排序的键值对 一=1 二=2 三=3 四=4 五=5

使用谷歌的番石榴图书馆

谷歌的番石榴库为我们提供了一个 ImmutableSortedMap 类。我们可以使用这个类的 copyOf()方法来对 HashMap 进行排序。我们需要将 HashMap 对象作为一个参数传递给这个方法,它将返回一个 ImmutableSortedMap 对象。返回的 ImmutableSortedMap 包含我们的 HashMap 中所有按键排序的条目。自然排序用于排序。

import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableSortedMap;

public class HashMapSortDemo
{
    public static void main(String args[])
    {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet())
        {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        //Creating an ImmutableSortedMap using the HashMap
        ImmutableSortedMap sortedMap = ImmutableSortedMap.copyOf(unsortedMap);

        System.out.println("\nPrinting the Sorted ImmutableSortedMap");
        System.out.println(sortedMap);
    }
}

打印未排序的HashMap 四- > 4 一- > 1 二- > 2 三- > 3 五->5 T7】打印已排序的不变HashMap {五=5,四=4,一=1,三=3,二=2}

总结

当我们想要存储键值对时,HashMap 是一个方便的集合。在内部,它使用HashMap的概念。没有内置的方法对HashMap进行排序。但是,我们可以通过使用ArrayListTreeSet等其他集合来查看排序后的HashMap条目。如果您想保持映射条目的排序顺序,树形映射是一个很好的选择。我们还可以将排序后的键值对存储在 LinkedHashMap 中。LinkedHashMap 维护元素的插入顺序,我们只需要对映射排序一次。