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.

Suppose we have some values in the following HashMap

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

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

package com.roytuts.lambda.foreach;
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 shown below

package com.roytuts.lambda.foreach;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MapArraylistLambdaTest {
	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

Thanks for reading.

Tags:

Leave a Reply

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