Java Collections – LinkedHashMap Example

The LinkedHashMap is a hash table and linked list based implementation of the map interface and represents a mapping between a key and a value with predictable ordering while iterating through the elements. A LinkedHashMap is roughly equivalent to HashTable except that it permits nulls and is unsynchronized. In the example I have detailed, it will represent a mapping of the baseball player’s ID and the player object which contains their full name, starting year and team they played for.

Big-O Notation

According to the Javadocs, this implementation provides constant-time O(1) performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Performance is said to be slightly slower than HashMap due to overhead in maintaining the linkedlist. However, performance for iterations should be faster than HashMap.

Creating a LinkedHashMap

This was the old-way prior to Generics.

LinkedHashMap players = new LinkedHashMap();

Generics

If you look closely, you will notice that I am using Generics to limit the type to String for the Key, and Integer for the Value in the Map. Generics add stability to your code, by having the computer detect type incompatibilities during compile-time. These runtime bugs would be more difficult to debug if left unchecked.

LinkedHashMap <String,Player> players = 
                         new LinkedHashMap<String,Player>();

LinkedHashMap Points

  • LinkedHashMap will maintain the insertion order. This will allow us to iterate through the set in the same order as the elements were inserted
  • Better than HashMap for iteration, as you know the ordering sequence
  • Performance of LinkedHashMap is slightly below HashMap
  • Faster implementation than that of TreeMap
  • LinkedHashMap are not thread safe, you may need to wrap in Collections.synchronizedSet()

Adding elements

Adding elements to the players Map is done by using the put(Object key, Object value) method. The key of the Map will be the player ID which is a String and the value will be an Player object.

players.put("101", babe);
players.put("102", ty);
players.put("103", lou);
players.put("104", ted);
players.put("105", hank);
players.put("106", yogi);
players.put("107", willie);
players.put("108", roberto);

Removing elements

Removing elements is just a matter of calling the remove(Object key) method.

players.remove("104");
players.remove("106");

Checking elements

You can see if object is in LinkedHashMap by calling the containsKey(String key) or containsValue(Object obj) method.

// Is 111 a key in this set? 
System.out.println("Is 111 in this set?"+players.containsKey("111"));
// Is willie in this set? 
System.out.println("Is willie in this set?"
                                    +players.containsValue(willie));
// Is yogi in this set? 
System.out.println("Is yogi in this set?"+players.containsValue(yogi));

Size of Collection

Returning the number of elements in a LinkedHashMap is as easy as calling the size() method.

players.size();

Iterating through the Collection

Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.

// Loop through the collection of players
for (String playerID : playerMap.keySet()) {
   count++;
   Player p =  playerMap.get(playerID);
   System.out.format("Player==> [%d]  %s started in [%d], 
       played for the %sn", count, p.getPlayerName(), 
       p.getStartYear(), p.getTeam());
}

Iterating through the Collection with Generics

Map<String,Player> players = new LinkedHashMap<String,Player>();
    
Iterator iterator = players.entrySet().iterator();
while (iterator.hasNext()) {
   count++;
  Map.Entry<String,Player> element = (Map.Entry) iterator.next();
   Player p = element.getValue();
   System.out.format("Player==> [%d]  %s started in [%d], 
       played for the %sn", count, p.getPlayerName(), 
       p.getStartYear(), p.getTeam());
}

Full Program Listing (LinkedHashMapExample.java)

package com.avaldes.tutorials;

import java.util.LinkedHashMap;

public class LinkedHashMapExample {

  public static void main(String[] args) {
    // Ensure that the LinkedHashMap only takes String for the key and Player 
    // for the value
    LinkedHashMap<String,Player> players = new LinkedHashMap<String,Player>();
    
    //Create all the players
    Player babe = new Player("Babe Ruth", 1914, "New York Yankees");
    Player ty = new Player("Ty Cobb", 1905, "Detroit Tigers");
    Player lou = new Player("Lou Gehrig", 1923, "New York Yankees");
    Player ted = new Player("Ted Williams", 1939, "Boston Redsox");
    Player hank = new Player("Hank Aaron", 1954, "Atlanta Braves");
    Player yogi = new Player("Yogi Berra", 1946, "New York Yankees");
    Player willie = new Player("Willie Mays", 1951, "San Francisco Giants");
    Player roberto = new Player("Roberto Clemente",1955,"Pittsburgh Pirates");
    Player mickey= new Player("Mickey Mantle", 1951, "New York Yankees");
    Player tom = new Player("Tom Seaver", 1967, "New York Mets");
    Player nolan = new Player("Nolan Ryan", 1966, "Texas Rangers");
    Player amaury = new Player("Amaury Valdes", 1975, "Newark Bears");
        
    // Populate the players LinkedHashMap  -- Auto-Boxing 
    players.put("101", babe);
    players.put("102", ty);
    players.put("103", lou);
    players.put("104", ted);
    players.put("105", hank);
    players.put("106", yogi);
    players.put("107", willie);
    players.put("108", roberto);
    players.put("109", mickey);
    players.put("110", tom);
    players.put("111", nolan);
    players.put("112", amaury);
    
    System.out.println("Display All Players -- prior to delete operation...");
    System.out.println(players);
    System.out.println("Number of Players: " + players.size());
    
    // Let's remove employee Ted Williams & Yogi Berra
    System.out.println("Removing Ted Williams from players");
    players.remove("104");
    System.out.println("Removing Yogi Berra from playersn");
    players.remove("106");
    
    System.out.println("Checking key and values in the set...");
    // Is 111 a key in this set? 
    System.out.println("Is 111 in this set? " + players.containsKey("111"));
    // Is willie in this set? 
    System.out.println("Is willie in this set? " 
                                   + players.containsValue(willie));
    // Is yogi in this set? 
    System.out.println("Is yogi in this set? " 
                                   + players.containsValue(yogi));
        
    System.out.println("Display All Players -- after delete operation...");
    displayAllPlayers(players);
    System.out.println("Number of Players: " + players.size());
    
  }

  static public void displayAllPlayers(
                              LinkedHashMap<String,Player> playerMap) {
    int count = 0;
    
    // Loop through the collection of employees 
    for (String playerID : playerMap.keySet()) {
      count++;
      Player p =  playerMap.get(playerID);
      // Format the output nicely
      System.out.format("Player==> [%d]  %s started in [%d], 
            played for the %sn", count, p.getPlayerName(), 
            p.getStartYear(), p.getTeam());
    }
  }
}

Full Program Listing (Player.java)

package com.avaldes.tutorials;

public class Player {
  private String playerName;
  private int startYear;
  private String  team;
  
  public Player(String name, int year, String team) {
    setPlayerName(name);
    setStartYear(year);
    setTeam(team);
  }
  
  public String getPlayerName() {
    return playerName;
  }
  public void setPlayerName(String playerName) {
    this.playerName = playerName;
  }
  public int getStartYear() {
    return startYear;
  }
  public void setStartYear(int startYear) {
    this.startYear = startYear;
  }
  public String getTeam() {
    return team;
  }
  public void setTeam(String team) {
    this.team = team;
  }
  
  @Override
    public String toString() {
       return playerName;
    }
}

Output

Display All Players -- prior to delete operation...
{101=Babe Ruth, 102=Ty Cobb, 103=Lou Gehrig, 104=Ted Williams, 105=Hank Aaron, 
106=Yogi Berra, 107=Willie Mays, 108=Roberto Clemente, 109=Mickey Mantle, 
110=Tom Seaver, 111=Nolan Ryan, 112=Amaury Valdes}
Number of Players: 12

Removing Ted Williams from players
Removing Yogi Berra from players


Checking key and values in the set...
Is 111 in this set? true
Is willie in this set? true
Is yogi in this set? false

Display All Players -- after delete operation...
Player==> [1]  Babe Ruth started in [1914], played for the New York Yankees
Player==> [2]  Ty Cobb started in [1905], played for the Detroit Tigers
Player==> [3]  Lou Gehrig started in [1923], played for the New York Yankees
Player==> [4]  Hank Aaron started in [1954], played for the Atlanta Braves
Player==> [5]  Willie Mays started in [1951], played for the San Francisco Giants
Player==> [6]  Roberto Clemente started in [1955], played for the Pittsburgh Pirates
Player==> [7]  Mickey Mantle started in [1951], played for the New York Yankees
Player==> [8]  Tom Seaver started in [1967], played for the New York Mets
Player==> [9]  Nolan Ryan started in [1966], played for the Texas Rangers
Player==> [10]  Amaury Valdes started in [1975], played for the Newark Bears
Number of Players: 10

Other Related Posts

Map Examples

List Examples

Set Examples

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *