18
16

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.

HashMap#keySetの返り値の中身がJava7とJava8で違う

Last updated at Posted at 2015-05-13

HashMapkeySet()で返されるキーの並び順が変わった

以下のソースをJava7、Java8それぞれで実行してみた。

Map#keySet
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");

System.out.println("keySet: " + map.keySet());

Java7の実行結果

Java7実行
// 降順で返ってくる
keySet: [key3, key2, key1]

Java8の実行結果

Java8実行結果
// 昇順で返ってくる
keySet: [key1, key2, key3]

解決方法

ソートする

一度配列にしてソートする。

ソートする
String[] keyArray = map.keySet().toArray(new String[map.size()]);
// 降順
Arrays.sort(keyArray, Collections.reverseOrder());
// 昇順
Arrays.sort(keyArray);

そもそも

Setに順序を期待してはいけない。
順序依存を期待したいのならSortedSetを実装したコレクションクラスを利用すべき。
順序付きのMapを使いたいのであればTreeMapを使う。
@pocariさん、@tsuyoshi_choさんコメントありがとうございます)

HashMap, TreeMap, LinkedHashMapkeySet()について

3つのMapそれぞれのkeySet()の出力結果を見てみる。

それぞれのMapのkeySet()
HashMap<String,String> hashMap = new HashMap<String, String>();
hashMap.put("key1", "value1");
hashMap.put("key3", "value3");
hashMap.put("key2", "value2");
System.out.println("HashMap.keySet: " + hashMap.keySet());
		
TreeMap<String,String> treeMap = new TreeMap<String, String>();
treeMap.put("key1", "value1");
treeMap.put("key3", "value3");
treeMap.put("key2", "value2");
System.out.println("TreeMap.keySet: " + treeMap.keySet());

LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String, String>();
linkedHashMap.put("key1", "value1");
linkedHashMap.put("key3", "value3");
linkedHashMap.put("key2", "value2");
System.out.println("LinkedHashMap.keySet: " + linkedHashMap.keySet());

Java7の実行結果

Java7実行結果
// 降順(順序は不定)
HashMap.keySet: [key3, key2, key1]
// 昇順(順序付き)
TreeMap.keySet: [key1, key2, key3]
// 挿入順
LinkedHashMap.keySet: [key1, key3, key2]

Java8の実行結果

Java8実行結果
// 昇順(順序は不定)
HashMap.keySet: [key1, key2, key3]
// 昇順(順序付き)
TreeMap.keySet: [key1, key2, key3]
// 挿入順
LinkedHashMap.keySet: [key1, key3, key2]
18
16
5

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
18
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?