Skip to content

Commit b400734

Browse files
Create LinkedHashMapDemo.java
1 parent 09d90e4 commit b400734

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package learnCollections;
2+
3+
import java.util.HashMap;
4+
import java.util.LinkedHashMap;
5+
import java.util.Map;
6+
7+
public class LinkedHashMapDemo {
8+
public static void main(String[] args) {
9+
// uses double linked list to maintain insertion order
10+
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>(11, 0.8f, true); // initial capacity = 11, load factor = 0.8, access order = true (maintains access order instead of insertion order, by default it's false)
11+
linkedHashMap.put("Orange", 10);
12+
linkedHashMap.put("Apple", 20);
13+
linkedHashMap.put("Guava", 30);
14+
15+
linkedHashMap.get("Apple");
16+
17+
for (Map.Entry<String, Integer> entry: linkedHashMap.entrySet()) {
18+
System.out.println(entry.getKey() + ": " + entry.getValue());
19+
}
20+
/*
21+
Orange: 10
22+
Guava: 30
23+
Apple: 20
24+
*/
25+
26+
27+
HashMap<String, Integer> hashMap = new HashMap<>();
28+
29+
hashMap.put("Shubham", 90);
30+
hashMap.put("Bob", 80);
31+
hashMap.put("Akshit", 78);
32+
33+
Integer res = hashMap.getOrDefault("Rahul", 0);
34+
hashMap.putIfAbsent("Shubham", 92); // won't update because key already exists
35+
System.out.println(hashMap);
36+
}
37+
}

0 commit comments

Comments
 (0)