[Java] HashMap, TreeMap, LinkedHashMap set values retention order

[Java] HashMap, TreeMap, LinkedHashMap set values retention order

There are several types of Map, but there is a difference in the order in which the stored values are retained (in which order they are output). I summarized it of the Maps that I often see (personally). I feel that which map to use is often selected due to this difference in characteristics.

HashMap TreeMap LinkedHashMap
Indefinite order Key ascending order Registration order

I checked it below.

test.java


public static void main(String[] args) {
	final int key = 0;
	final int value = 1;
	HashMap<String,String> hashMap = new HashMap<String,String>();
	TreeMap<String,String> treeMap = new TreeMap<String,String>();
	LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<String,String>();

	String[][] keyValue = {{"Japan","America","China","Korea","India"},
							{"Tokyo","Washington D.C.","Beijing","Seoul","New Delhi"}};

	for(int i = 0; i < keyValue[key].length; i++) {
		hashMap.put(keyValue[key][i], keyValue[value][i]);
		treeMap.put(keyValue[key][i], keyValue[value][i]);
		linkedHashMap.put(keyValue[key][i], keyValue[value][i]);
	}
	System.out.println("Output the result of HashMap!");
	for(String hashMapKey : hashMap.keySet()) {
		System.out.println( hashMapKey +"The capital of"+ hashMap.get(hashMapKey) + "is.");
		}
	System.out.println();

	System.out.println("Output TreeMap results!");
	for(String treeMapKey :treeMap.keySet()) {
		System.out.println( treeMapKey +"The capital of"+ treeMap.get(treeMapKey) + "is.");
	}
	System.out.println();

	System.out.println("Output the result of LinkedHashMap!");
	for(String linkedHashMapKey : linkedHashMap.keySet()) {
		System.out.println( linkedHashMapKey +"The capital of"+ linkedHashMap.get(linkedHashMapKey) + "is.");
	}
}

Execution result


Output the result of HashMap!
The capital of Japan is Tokyo.
The capital of China is Beijing.
The capital of America is Washington D.C.is.
The capital of Korea is Seoul.
The capital of India is New Delhi.

Output the result of TreeMap!
The capital of America is Washington D.C.is.
The capital of China is Beijing.
The capital of India is New Delhi.
The capital of Japan is Tokyo.
The capital of Korea is Seoul.

Output the result of LinkedHashMap!
The capital of Japan is Tokyo.
The capital of America is Washington D.C.is.
The capital of China is Beijing.
The capital of Korea is Seoul.
The capital of India is New Delhi.

Therefore, it was confirmed that HashMap is in an indefinite order, TreeMap is in ascending order of keys (this time in ascending order of alphabet), and LinkedHashMap is in registration order. Well, I forget it every time.

Recommended Posts

[Java] HashMap, TreeMap, LinkedHashMap set values retention order
Sort Map values in ascending key order in Java TreeMap
Java (set)
Java HashMap class