6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaでキーでソートされた重複のないMap

Last updated at Posted at 2017-03-14

こんにちはsekitakaです。

HashMapのキーでソートしたいなと思い調べたところ、TreeMapというものがあり便利だったので紹介します。
TreeMapはHashMap同様キーの重複がないMapです。
それに加えてキーでのソートが自動で行われます。

使い方

TreeMap<String,String> treeMap = new TreeMap<>();
treeMap.put("2","2");
treeMap.put("b","B");
treeMap.put("1","1");
treeMap.put("a","A");
treeMap.put("1","1(2回目)");
System.out.println(treeMap); 

以下の結果が出力されます。

{1=1(2回目), 2=2, a=A, b=B}

期待したとおりキーでソートされ、キーの重複がなくなっています。

カスタムソート

デフォルトのソート順はJavaの自然順序付けですが、以下のようにコンストラクタにComparatorを指定することで、独自のソートロジックを指定することも可能です。

TreeMap<String,String> treeMap = new TreeMap<>(new Comparator<String>(){
    @Override
    public int compare(String o1, String o2) {
        // [略]カスタムソートのロジック
    }
});

まとめ

いかがでしたでしょうか。Javaは標準ライブラリが豊富なので探せば色々と便利なクラスが見つかるものですね。

6
6
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?