HashMap 排序

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

HashMap 是一种存储键值对的集合。然而,它不会以任何特定顺序存储键值对,也不会维护元素的插入顺序。在某些情况下,我们可能希望以排序的方式查看存储的数据。在这种情况下,我们需要对 HashMap 进行排序。

创建一个新的 Java 文件

首先,我们需要创建一个新的 Java 文件来编写排序 HashMap 的代码。打开终端并导航到你想要创建文件的目录。使用以下命令创建一个名为 HashMapSortDemo.java 的新文件。

touch HashMapSortDemo.java

使用 Collections.sort() 按键排序

我们可以使用 Collections.sort() 方法对 HashMap 按键进行排序。参考以下代码:

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());
        }

        ArrayList<String> sortedList = new ArrayList<>(unsortedMap.keySet());
        Collections.sort(sortedList);

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

上述代码使用 Collections.sort() 方法对 HashMap 按键进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 Collections.sort() 按值排序

我们可以使用 Collections.sort() 方法对 HashMap 按值进行排序。参考以下代码:

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());
        }

        ArrayList<Integer> sortedList = new ArrayList<>(unsortedMap.values());
        Collections.sort(sortedList);

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

上述代码使用 Collections.sort() 方法对 HashMap 按值进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 TreeMap 按键排序

我们可以使用 TreeMap 对 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);

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

上述代码使用 TreeMap 对 HashMap 按键进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 TreeSet 按值排序

我们可以使用 TreeSet 对 HashMap 按值进行排序。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);

        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());
        }

        TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());

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

上述代码使用 TreeSet 对 HashMap 按值进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 Stream 和 Lambda 表达式排序

我们可以通过 Java Streams 和 Lambda 表达式,用一行代码对 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<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.<String, Integer>comparingByKey());

        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);
    }
}

上述代码使用 Java Streams 和 Lambda 表达式对 HashMap 进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 Stream 和 Lambda 表达式按值排序

我们也可以使用 Java Streams 和 Lambda 表达式对 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<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.<String, Integer>comparingByValue());

        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);
    }
}

上述代码使用 Java Streams 和 Lambda 表达式对 HashMap 按值进行排序。

使用以下命令编译并运行代码:

javac HashMapSortDemo.java && java HashMapSortDemo

使用 Google 的 Guava 库

Google 的 Guava 库为我们提供了 ImmutableSortedMap 类。我们可以使用该类的 copyOf() 方法对 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());
        }

        ImmutableSortedMap<String, Integer> sortedMap = ImmutableSortedMap.copyOf(unsortedMap);

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

上述代码使用 Google 的 Guava 库对 HashMap 进行排序。

使用以下命令编译并运行代码:

javac -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo.java && java -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo

清理

最后,使用以下命令删除 HashMapSortDemo.java 文件:

rm HashMapSortDemo.java

总结

在本实验中,我们学习了如何通过键或值对 HashMap 进行排序。我们使用了不同的方法,例如 Collections.sort()TreeMapTreeSet、Java Streams 和 Lambda 表达式,以及 Google 的 Guava 库来对 HashMap 进行排序。我们还了解了它们的使用场景,以及如何编写高效的代码来在 Java 中对 HashMap 进行排序。

您可能感兴趣的其他 Java 教程