Map To List Objects
Here I will show you how to convert List
of Map
objects into List
of objects using Java 8’s or later’s 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+
Convert List of Map to List Objects
Let’s say you have the following List of Map objects as a result coming from database table while you are selecting multiple records using SQL statement from the database table.
List<Map<String, Object>> results = jdbcTemplate.queryForList("SELECT * FROM cd");
Now you 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 it is assumed that you have a POJO class Cd
with id
, title
and artist
attributes and corresponding getters/setters. It is also assumed that you also have created the required database table in the database server.
Now the resultant List<Cd>
cds
can be used anywhere in the application.