Java LinkedHashMap Example

In this article, we will discuss important LinkedHashMap class methods with examples.
The HashMap class doesn’t guarantee any specific iteration order of the elements. It doesn’t keep track of the order in which the elements are inserted and produces the elements in a random order every time you iterate over it.
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. It inherits the HashMap class and implements the Map interface.
The important points about Java LinkedHashMap class are:
  • A LinkedHashMap contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It is the same as HashMap instead maintains insertion order.
  • Unlike HashMap, the iteration order of the elements in a LinkedHashMap is predictable.
  • Just like HashMap, LinkedHashMap is not thread-safe. You must explicitly synchronize concurrent access to a LinkedHashMap in a multi-threaded environment.

Creating and Initializing a LinkedHashMap Example

The following example shows how to create a LinkedHashMap and add new key-value pairs to it.
// Creating a LinkedHashMap
LinkedHashMap<String, Integer> dayNumberMapping = new LinkedHashMap<>();

// Adding new key-value pairs to the LinkedHashMap
dayNumberMapping.put("Mon", 1);
dayNumberMapping.put("Tus", 2);
dayNumberMapping.put("Wen", 3);
dayNumberMapping.put("Thu", 4);
dayNumberMapping.put("Fri", 5);
dayNumberMapping.put("Sat", 6);

// Add a new key-value pair only if the key does not exist 
// in the LinkedHashMap, or is mapped to `null`
dayNumberMapping.putIfAbsent("Sun", 7);

System.out.println(dayNumberMapping);
Output:
{Mon=1, Tus=2, Wen=3, Thu=4, Fri=5, Sat=6, Sun=7}

put(String key, Integer value) method example

Associates the specified value with the specified key in this map (optional operation).
// Creating a HashMap
LinkedHashMap<String, Integer> dayNumberMapping = new LinkedHashMap<>();
// Adding new key-value pairs to the LinkedHashMap
dayNumberMapping.put("Mon", 1);
dayNumberMapping.put("Tus", 2);
dayNumberMapping.put("Wen", 3);

putIfAbsent(String key, Integer value) method example

If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
LinkedHashMap<String, Integer> dayNumberMapping = new LinkedHashMap<>();
dayNumberMapping.putIfAbsent("Sun", 7);

4. LinkedHashMap API's for accessing keys and modifying their associated value

  • How to check if a LinkedHashMap is empty | isEmpty()
  • How to find the size of a LinkedHashMap| size()
  • How to check if a given key exists in a LinkedHashMap| containsKey()
  • How to check if a given value exists in a LinkedHashMap| containsValue()
  • How to get the value associated with a given key in the LinkedHashMap| get()
  • How to modify the value associated with a given key in the LinkedHashMap| put()

isEmpty() method example

Returns true if this map contains no key-value mappings.
Map<String, String> userCityMapping = new LinkedHashMap<>();

// Check if a HashMap is empty
System.out.println("is userCityMapping empty? : " + userCityMapping.isEmpty());

size() method example

Returns the number of key-value mappings in this map. If the map contains more than Integer.MAX_VALUE elements return Integer.MAX_VALUE.
Map<String, String> userCityMapping = new LinkedHashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");
// Find the size of a HashMap
System.out.println("We have the city information of " + userCityMapping.size() + " users");

containsKey(Object key) method example

Returns true if this map contains a mapping for the specified key. More formally, returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null: key.equals(k)). (There can be at most one such mapping.)
Map<String, String> userCityMapping = new LinkedHashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

String userName = "Steve";
// Check if a key exists in the HashMap
if(userCityMapping.containsKey(userName)) {
    // Get the value assigned to a given key in the HashMap
    String city = userCityMapping.get(userName);
    System.out.println(userName + " lives in " + city);
} else {
    System.out.println("City details not found for user " + userName);
}

containsValue(Object value) method example

Returns true if this map maps one or more keys to the specified value. 
Map<String, String> userCityMapping = new LinkedHashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

// Check if a value exists in a HashMap
if(userCityMapping.containsValue("New York")) {
 System.out.println("There is a user in the userCityMapping who lives in New York");
} else {
 System.out.println("There is not user in the userCityMapping who lives in New York");
}

get(Object key) method example

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Map<String, String> userCityMapping = new LinkedHashMap<>();
userCityMapping.put("John", "New York");
userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Steve", "London");

System.out.println("Lisa's city : " + userCityMapping.get("Steve"));

5. LinkedHashMap remove API's with Examples

  • Remove a key from a LinkedHashMap | remove(Object key)
  • Remove a key from a LinkedHashMap only if it is associated with a given value | remove(Object key, Object value)

remove(Object key) method example

Removes the mapping for a key from this map if it is present (optional operation). 
Map<String, String> husbandWifeMapping = new LinkedHashMap<>();
husbandWifeMapping.put("Jack", "Marie");
husbandWifeMapping.put("Chris", "Lisa");
husbandWifeMapping.put("Steve", "Jennifer");

String husband = "Chris";
String wife = husbandWifeMapping.remove(husband);

remove(Object key, Object value) method example

Removes the entry for the specified key only if it is currently mapped to the specified value.
Map<String, String> husbandWifeMapping = new LinkedHashMap<>();
husbandWifeMapping.put("Jack", "Marie");
husbandWifeMapping.put("Chris", "Lisa");
husbandWifeMapping.put("Steve", "Jennifer");

// Remove a key from the HashMap only if it is mapped to the given value
// Ex - Divorce "Jack" only if He is married to "Linda"
boolean isRemoved = husbandWifeMapping.remove("Jack", "Linda");
System.out.println("Did Jack get removed from the mapping? : " + isRemoved);

Iterating over a LinkedHashMap

The example in this section shows various ways of iterating over a LinkedHashMap:
  • Iterate over a LinkedHashMap using Java 8 forEach and lambda expression.
  • Iterate over a LinkedHashMap’s entrySet using Java 8 forEach and lambda expression.
  • Iterate over a LinkedHashMap’s entrySet using iterator().
  • Iterate over a LinkedHashMap’s entrySet using iterator() and Java 8 forEachRemaining() method.

Iterate over a LinkedHashMap using Java 8 forEach and lambda expression

LinkedHashMap<String, String> userCityMapping = new LinkedHashMap<>();

userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Chris", "London");
userCityMapping.put("David", "Paris");
userCityMapping.put("Jesse", "California");

userCityMapping.forEach((user, city) -> {
 System.out.println(user + " => " + city);
});

Iterating over the LinkedHashMap's entrySet using Java 8 forEach and lambda

LinkedHashMap<String, String> userCityMapping = new LinkedHashMap<>();

userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Chris", "London");
userCityMapping.put("David", "Paris");
userCityMapping.put("Jesse", "California");

userCityMapping.entrySet().forEach(entry -> {
 System.out.println(entry.getKey() + " => " + entry.getValue());
});

Iterating over the entrySet of a LinkedHashMap using iterator()

LinkedHashMap<String, String> userCityMapping = new LinkedHashMap<>();

userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Chris", "London");
userCityMapping.put("David", "Paris");
userCityMapping.put("Jesse", "California");

Iterator<Map.Entry<String, String>> userCityMappingIterator 
         = userCityMapping.entrySet().iterator();
while (userCityMappingIterator.hasNext()) {
 Map.Entry<String, String> entry = userCityMappingIterator.next();
 System.out.println(entry.getKey() + " => " + entry.getValue());
}

Iterating over the entrySet of a LinkedHashMap using iterator() and forEachRemaining()

LinkedHashMap<String, String> userCityMapping = new LinkedHashMap<>();

userCityMapping.put("Rajeev", "Bengaluru");
userCityMapping.put("Chris", "London");
userCityMapping.put("David", "Paris");
userCityMapping.put("Jesse", "California");

userCityMappingIterator = userCityMapping.entrySet().iterator();
userCityMappingIterator.forEachRemaining(entry -> {
 System.out.println(entry.getKey() + " => " + entry.getValue());
});

LinkedHashMap Maintain Insertion Order Example

public class MapInterfaceLinkedHashMapImpl {

 public static void main(String[] args) {
  linkedHashMap();
 }

 // Maintain insertion order.
 private static void linkedHashMap() {
  // Constructs an empty insertion-ordered LinkedHashMap instance with the
  // default
  // initial capacity (16) and load factor (0.75).
  Map<String, String> linkedHahMap = new LinkedHashMap<>();
  linkedHahMap.put("key1", "value1");
  linkedHahMap.put("key3", "value3");
  linkedHahMap.put("key2", "value2");
  linkedHahMap.put("key0", "value0");

  // loop linkedHahMap using java 8 forEach method
  linkedHahMap.forEach((k, v) -> {
   System.out.println(k);
   System.out.println(v);
  });

  // loop linkedHahMap using before java 8 forEach method
  for (Entry pair : linkedHahMap.entrySet()) {
   System.out.println(pair.getKey());
   System.out.println(pair.getValue());
  }
 }
}
Output:
key1
value1
key3
value3
key2
value2
key0
value0
key1
value1
key3
value3
key2
value2
key0
value0

Related Collections Examples

Comments