Introduction

Here we will see how to convert List of Map objects into List of objects using Java Stream API. The List of Map objects can be found as a result of selecting multiple records from database table or any other sources. Then you may need to convert into List of objects to make it better readability for further using in the application code.

Prerequisites

Java 1.8

Example

Let’s say we have the following List of Map objects as a result coming from database table while we are selecting multiple records using SQL statement.

List<Map<String, Object>> results = jdbcTemplate.queryForList("SELECT * FROM cd");

Now we need to convert the above List of Map objects into List of objects as an application requirement for further using into some other part of the application.

The below code snippets will convert using Java Stream API.

List<Cd> cds = results.stream().map(m -> {
	Cd cd = new Cd();
	cd.setId(Long.parseLong(String.valueOf(m.get("id"))));
	cd.setTitle(String.valueOf(m.get("title")));
	cd.setArtist(String.valueOf(m.get("artist")));
	return cd;
}).collect(Collectors.toList());

In the above code snippets we are assuming we have a POJO class Cd with id, title and artist attributes and corresponding getters/setters.

Now the resultant List<Cd> cds can be used anywhere in the application.

Thanks for reading.

Tags:

Leave a Reply

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