0

LinkedHashMap

Khi sử dụng Map để tạo một map key-value, đôi khi chúng ta cần get ra cặp key-value theo index mà chúng được put vào map. Bình thường khi sử dụng HashMap, thì theo như https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html: Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. Thứ tự các cặp key-value sẽ không được đảm bảo là giống như thứ tự chúng được put vào. Để làm điều đó thì có thể sử dụng LinkedHashMap, thứ tự sẽ được giữ nguyên khi put vào, bạn có thể lấy giá trị theo index bằng linkedHashMap.values().toArray()[1]. Demo:

HashMap<Integer, String> hashMap = new HashMap<>();
		hashMap.put(5, "Five");
		hashMap.put(1, "One");
		hashMap.put(2, "Two");
		Iterator<Integer> hashMapIterator = hashMap.keySet().iterator();
		while (hashMapIterator.hasNext()) {
			Integer key = hashMapIterator.next();
			String value = hashMap.get(key);
			System.out.println(key + " " + value);
		}
		System.out.println("Value at index 1 = " + hashMap.values().toArray()[1]);
		System.out.println("--------------------------");
		LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
		linkedHashMap.put(5, "Five");
		linkedHashMap.put(1, "One");
		linkedHashMap.put(2, "Two");
		Iterator<Integer> linkedHashMapIterator = linkedHashMap.keySet().iterator();
		while (linkedHashMapIterator.hasNext()) {
			Integer key = linkedHashMapIterator.next();
			String value = linkedHashMap.get(key);
			System.out.println(key + " " + value);
		}
		System.out.println("Value at index 1 = " + linkedHashMap.values().toArray()[1]);

**Output: **

1 One
2 Two
5 Five
Value at index 1 = Two
--------------------------
5 Five
1 One
2 Two
Value at index 1 = One

All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí