HashMap のソート

JavaBeginner

はじめに

HashMap は、キーと値のペアを格納するコレクションです。ただし、キーと値のペアを特定の順序で格納するわけではなく、要素の挿入順序を維持しません。データをソートされた形式で表示したい場合があります。そのような場合、HashMap をソートする必要があります。

新しい Java ファイルを作成する

まず、HashMap をソートするコードを記述するための新しい Java ファイルを作成する必要があります。ターミナルを開き、ファイルを作成したいディレクトリに移動します。次のコマンドを使用して、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 とラムダ式を使ったソート

Java の Stream とラムダ式を使うことで、HashMap を 1 行のコードでソートすることができます。以下のコードを参照してください。

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 の Stream とラムダ式を使って HashMap をソートしています。

コードをコンパイルして実行するには、次のコマンドを使用します。

javac HashMapSortDemo.java && java HashMapSortDemo

Stream とラムダ式を使った値によるソート

Java の Stream とラムダ式を使って、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 の Stream とラムダ式を使って 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()、TreeMap、TreeSet、Java Streams とラムダ式、そして Google の Guava ライブラリなど、さまざまな方法を使って HashMap をソートしました。また、それらの使用例と、Java で HashMap をソートするための効率的なコードの書き方についても学びました。