Convert a Map to Set, List or an Array

Convert a Map to Set, List or an Array

In this tutorial we will discuss how to perform the conversion of Map to several different collections. More specifically, we will learn how to convert a Map to Set, List and an Array using Java. I wanted to show you how to perform these conversions because these are the most commonly used data structures in Java.

In the following examples, you will notice that I am using LinkHashMap instead of the normal HashMap because I wanted to ensure that we keep the insertion order intact when converting to the other structures since I am converting both the keys and associated values. Otherwise, the keys would not remain in-sync with the values once the data is extracted from our Map. I need to ensure that k_element[0] of the keys array corresponds to v_element[0] from the values array.

What’s Covered

  1. Getting Started
  2. Complete Project Overview
  3. Java Collections Framework
  4. Map Hierarchy in Java Collections Framework
  5. Collections Hierarchy in Java Collections Framework
  6. Convert LinkedHashmap to Array
  7. Convert LinkedHashmap to Array Output
  8. Convert LinkedHashmap to List
  9. Convert LinkedHashmap to List Output
  10. Convert LinkedHashmap to Set
  11. Convert LinkedHashmap to Set Output
  12. Convert a Map to Set, List or an Array in Java — Complete Code

Getting Started

In order to run this tutorial yourself, you will need the following:

  • Java JDK 6 or greater
  • Favorite IDE Spring Tool Suite (STS), Eclipse IDE or NetBeans (I happen to be using STS because it comes with a Tomcat server built-in)
  • Tomcat 7 or greater or other popular container (Weblogic, Websphere, Glassfish, JBoss, VMWare vFabric, etc). For this tutorial I am using VMware vFabric tc Server Developer Edition which is essentially an enhanced Tomcat instance integrated with Spring STS

Complete Project Overview

I have added the project overview to give you a full view of the structure and show you all files contained in this sample project.

convert_map_proj_struct

Java Collections Framework

When Java was first released it only included a limited subset of useful data structures: Vector, Stack, HashTable, Dictionary, BitSet and the Enumeration interface. However, when Java 2 rolled out to the masses it included a full set of data structures. The Java development team set out with the following criteria:

  • Library needed to be small and easy to learn
  • Benefit of generic algorithms
  • Legacy classes needed to fit into the new framework

The Java Collections Framework (JCF) separates interfaces and their implementations. The collections framework also contains many concrete implementations that you may begin using immediately such as HashMap, LinkedList, ArrayList, HashSet and TreeSet.

Map Hierarchy in Java Collections Framework

map_hierarchy

Collections Hierarchy in Java Collections Framework

collection_hierarchy

Convert LinkedHashmap (MAP) to Array

In this example, we create an instance of LinkedHashMap collection called players. Since I am using generics, we specifically define that the LinkedHashMap will have a key of type
String and a value of type Player defined as LinkedHashMap<String, Player>.

In order to create an array of keys we use the toArray() method. The actual line where conversion takes place looks like: String[] keysArray = (String[]) players.keySet().toArray(new String[0]).

Please Note

We need to ensure we cast the object array to a String[] array otherwise the method returns an Object[] array. Additionally, we must pass an instance based on the type of object being created so that the toArray() method may infer the correct type to return. Lastly, since we know the number of elements in the array we need to create, players.keySet().size() and players.values().size(), we can pass this information at runtime to improve performance.

(String[]) players.keySet().toArray(new String[size])

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, into LinkedHashMap
  players.put("101", 
           new Player("Babe Ruth", 1914, "New York Yankees"));
  players.put("107", 
           new Player("Willie Mays", 1951, "San Francisco Giants"));
  players.put("110", 
           new Player("Tom Seaver", 1967, "New York Mets"));
  players.put("111", 
           new Player("Nolan Ryan", 1966, "Texas Rangers"));
  players.put("112", 
           new Player("Amaury Valdes", 1975, "Newark Bears"));

  // Convert LinkedHashmap to Array
  String[] keysArray = (String[]) players.keySet()
                        .toArray(new String[players.keySet().size()]);
  Player[] playerArray =  (Player[]) players.values()
                        .toArray(new Player[players.values().size()]);

  System.out.println("Keys Array...: "+Arrays.toString(keysArray));
  System.out.println("Players Array: "+Arrays.toString(playerArray));
  System.out.println();
}

Convert LinkedHashmap (MAP) to Array Output

Keys Array....: [101, 107, 110, 111, 112]

Players Array.: [Player [playerName:Babe Ruth, startYear:1914, 
team:New York Yankees], Player [playerName:Willie Mays, 
startYear:1951, team:San Francisco Giants], Player 
[playerName:Tom Seaver, startYear:1967, team:
New York Mets], Player [playerName:Nolan Ryan, startYear:1966, 
team:Texas Rangers], Player [playerName:Amaury Valdes, 
startYear:1975, team:Newark Bears]]

Convert LinkedHashmap (MAP) to List

Converting a Map to List is a relatively simple operation. This example describes how to create a List, or more specifically an ArrayList by passing the players’ set of keys using keySet() method which will return a Set of keys contained in the map, in the constructor of ArrayList(). In order to retrieve a collection of all of the values in the map we will use the values() method in the constructor of ArrayList().

List keyList = new ArrayList(players.keySet())
List playerList = new ArrayList(players.values())

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, into LinkedHashMap
  players.put("101", 
           new Player("Babe Ruth", 1914, "New York Yankees"));
  players.put("107", 
           new Player("Willie Mays", 1951, "San Francisco Giants"));
  players.put("110", 
           new Player("Tom Seaver", 1967, "New York Mets"));
  players.put("111", 
           new Player("Nolan Ryan", 1966, "Texas Rangers"));
  players.put("112", 
           new Player("Amaury Valdes", 1975, "Newark Bears"));

  // Convert LinkedHashmap to List
  List<String> keyList = new ArrayList<String>(players.keySet());
  List<Player> playerList = new ArrayList<Player>(players.values());

  System.out.println("Keys List.....: " + keyList.toString());
  System.out.println("Players List..: " + playerList.toString());
  System.out.println();
}

Convert LinkedHashmap (MAP) to List Output

Keys List.....: [101, 107, 110, 111, 112]
    
Players Array.: [Player [playerName:Babe Ruth, startYear:1914, 
team:New York Yankees], Player [playerName:Willie Mays, 
startYear:1951, team:San Francisco Giants], Player 
[playerName:Tom Seaver, startYear:1967, team:
New York Mets], Player [playerName:Nolan Ryan, startYear:1966, 
team:Texas Rangers], Player [playerName:Amaury Valdes, 
startYear:1975, team:Newark Bears]]

Convert LinkedHashmap (MAP) to Set

For this last example we will convert our LinkedHashMap to a Set, or more specifically a LinkedHashSet by passing the players’ set of keys using keySet() method in the constructor of LinkedHashSet(). In order to retrieve a collection of all of the values in the map we will use the values() method in the constructor of LinkedHashSet().

Set keySet = new LinkedHashSet(players.keySet())
Set playerSet = new LinkedHashSet(players.values())

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, into LinkedHashMap
  players.put("101", 
           new Player("Babe Ruth", 1914, "New York Yankees"));
  players.put("107", 
           new Player("Willie Mays", 1951, "San Francisco Giants"));
  players.put("110", 
           new Player("Tom Seaver", 1967, "New York Mets"));
  players.put("111", 
           new Player("Nolan Ryan", 1966, "Texas Rangers"));
  players.put("112", 
           new Player("Amaury Valdes", 1975, "Newark Bears"));

  // Convert LinkedHashmap to Set
  Set<String> keySet = new LinkedHashSet<String>(players.keySet());
  Set<Player> playerSet = new LinkedHashSet<Player>(players.values());

  System.out.println("Keys Set......: " + keySet.toString());
  System.out.println("Players Set...: " + playerSet.toString());
}

Convert LinkedHashmap (MAP) to Set Output

Keys Set......: [101, 107, 110, 111, 112]

Players Set...: [Player [playerName:Babe Ruth, startYear:1914, 
team:New York Yankees], Player [playerName:Willie Mays, 
startYear:1951, team:San Francisco Giants], Player 
[playerName:Tom Seaver, startYear:1967, team:
New York Mets], Player [playerName:Nolan Ryan, startYear:1966, 
team:Texas Rangers], Player [playerName:Amaury Valdes, 
startYear:1975, team:Newark Bears]]

Convert a Map to Set, List or an Array in Java — Complete Code

package com.avaldes.tutorials;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class ConvertMapExamples {

 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, into LinkedHashMap
  players.put("101", 
      new Player("Babe Ruth", 1914, "New York Yankees"));
  players.put("107", 
      new Player("Willie Mays", 1951, "San Francisco Giants"));
  players.put("110", 
      new Player("Tom Seaver", 1967, "New York Mets"));
  players.put("111", 
      new Player("Nolan Ryan", 1966, "Texas Rangers"));
  players.put("112", 
      new Player("Amaury Valdes", 1975, "Newark Bears"));

  // Convert LinkedHashmap to Array
  String[] keysArray = (String[]) players.keySet()
                        .toArray(new String[players.keySet().size()]);
  Player[] playerArray = (Player[]) players.values()
                        .toArray(new Player[players.values().size()]);

  System.out.println("Keys Array....: "+Arrays.toString(keysArray));
  System.out.println("Players Array.: "+Arrays.toString(playerArray));
  System.out.println();

  // Convert LinkedHashmap to List
  List<String> keyList = new ArrayList<String>(players.keySet());
  List<Player> playerList = new ArrayList<Player>(players.values());

  System.out.println("Keys List.....: " + keyList.toString());
  System.out.println("Players List..: " + playerList.toString());
  System.out.println();

  // Convert LinkedHashmap to Set
  Set<String> keySet = new LinkedHashSet<String>(players.keySet());
  Set<Player> playerSet = new LinkedHashSet<Player>(players.values());

  System.out.println("Keys Set......: " + keySet.toString());
  System.out.println("Players Set...: " + playerSet.toString());
 }
}

Download the Complete Source Code

That’s It!

I hope you enjoyed this tutorial. It was certainly a lot of fun putting it together and testing it out. Please continue to share the love and like us so that we can continue bringing you quality tutorials. Happy Coding!!!

java_convert_map

Core Java Related Tutorials

Please Share Us on Social Media

Facebooktwitterredditpinterestlinkedinmail

Leave a Reply

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