Sunday, 5 April 2015

Java LinkedHashMap Example


  • A LinkedHashMap contains values based on the key. It implements the Map interface and extends HashMap class.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is same as HashMap instead maintains insertion order.
  • You can also create a LinkedHashMap that returns its elements in the order in which they were last accessed.


Hierarchy of LinkedHashMap class:
                               
Example of LinkedHashMap class:

import java.util.LinkedHashMap;

public class LinkedHashMapDemo {
public static void main(String[] args) {

LinkedHashMap<Integer, Integer> linkedMap = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < 10; i++) {
linkedMap.put(i, i);
}

System.out.println(linkedMap);
// Least-recently used order:
linkedMap = new LinkedHashMap<Integer, Integer>(16, 0.75f, true);

for (int i = 0; i < 10; i++) {
linkedMap.put(i, i);
}
System.out.println(linkedMap);

for (int i = 0; i < 7; i++) {
System.out.println(linkedMap.get(i));
}

System.out.println(linkedMap);
}
}

Output:

{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
{0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}
0
1
2
3
4
5
6
{7=7, 8=8, 9=9, 0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6}

No comments:

Post a Comment