Java 8 : Iterate Map And Add To List

Here I will show you how to iterate Map in Java 8 and add element to List. I came across a situation where I required to fetch data from a HashMap and add it to an ArrayList. So I will show you here how to iterate a Map and form an object and finally add it to the List using Java 8 lambda expression.

Prerequisites

Java 1.8+

Map Iteration

Suppose you have some values in a HashMap as shown below:

Map<String, String> propertiesMap = new HashMap<>();
propertiesMap.put("success", "Success");
propertiesMap.put("warning", "Warning");
propertiesMap.put("error", "Error");

Now I have the below POJO class and for each key/value pair from the above Map you may need to form objects using the below POJO class and need to add each object to the List.

package com.roytuts.java.maptolist;

public class ConfigProperty {

	private String name;
	private String value;

	public ConfigProperty(String name, String value) {
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}

	public String getValue() {
		return value;
	}

}

Now iterate the Map and form the object using the above class and add each object to the List.

List<ConfigProperty> configProperties = new ArrayList<>();
propertiesMap.forEach((k, v) -> configProperties.add(new ConfigProperty(k, v)));

The full source code is given below how to iterate a Map and add to List:

package com.roytuts.java.maptolist;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class App {

	public static void main(String[] args) {
		
		Map<String, String> propertiesMap = new HashMap<>();
		propertiesMap.put("success", "Success");
		propertiesMap.put("warning", "Warning");
		propertiesMap.put("error", "Error");
		
		List<ConfigProperty> configProperties = new ArrayList<>();
		
		propertiesMap.forEach((k, v) -> configProperties.add(new ConfigProperty(k, v)));
		
		configProperties.forEach(c -> System.out.println(c.getName() + " => " + c.getValue()));
	}

}

When you run the above class you will see the below output in the console:

success => Success
warning => Warning
error => Error

Source Code

Download

Leave a Reply

Your email address will not be published.