How can I convert List of LinkedHashMap to List of Custom Object using Java 8

Viewed 422

How can we convert List<LinkedHashMap> in to List of Custom Object (List<Employee>) using Java 8 Streams.

Example : List<LinkedHashMap>

Here name and designation both are LinkedHashmap key. if you copy below snippet in IDE you can have better understand of this List<LinkedHashMap>.

List<LinkedHashMap> list = new ArrayList<>();
LinkedHashMap<String, String> linkedHashMap1 = new LinkedHashMap<>((Map.of("name","David", "designation","Senior Software Engineer")));
LinkedHashMap<String, String> linkedHashMap2 = new LinkedHashMap<>((Map.of("name","Alex", "designation","Software Engineer")));
LinkedHashMap<String, String> linkedHashMap3 = new LinkedHashMap<>((Map.of("name","Jessi","designation","Lead")));
LinkedHashMap<String, String> linkedHashMap4 = new LinkedHashMap<>((Map.of("name","Martin","designation","Manager")));

list.add(linkedHashMap1);
list.add(linkedHashMap2);
list.add(linkedHashMap3);
list.add(linkedHashMap4);
System.out.println(list);

Need to convert above List<LinkedHashmap> to List<Employee> Where Employee class has below two fields :

Class Employee {
String name;
String designation;
}

Expected output :

[Employee(name = David, designation = Senior Software Engineer), 
Employee(name = Alex, designation = Software Engineer), 
Employee(name = Jessi, designation = Lead),
Employee(name = Martin, designation = Manager)]      
2 Answers

Create a stream over the source list. And transform every map in the list into an instance of Employee using the values mapped to the keys "name" and "designation".

public static void main(String[] args) {
    List<Map<String, String>> source = List.of(
            Map.of("name","David", "designation","Senior Software Engineer"),
            Map.of("name","Alex", "designation","Software Engineer"),
            Map.of("name","Jessi","designation","Lead"),
            Map.of("name","Martin","designation","Manager"));

    List<Employee> result = source.stream()
            .map(map -> new Employee(map.get("name"), map.get("designation")))
            .collect(Collectors.toList());

    result.forEach(System.out::println);
}

Output

Employee{name='David', designation='Senior Software Engineer'}
Employee{name='Alex', designation='Software Engineer'}
Employee{name='Jessi', designation='Lead'}
Employee{name='Martin', designation='Manager'}

Note:

  • It's not a good practice to store an object as a map. In your example, nothing can save you from typo, and you will get null instead of an attribute value.
  • Don't drop the generic information.

Using streams you can use the code below providing that your Employe class has a constructor with this signature: public Employe(String name, String designation).

List<Employe> customList= list.stream()
    .flatMap(map -> map.entrySet().stream())
    .map(entry -> new Employe(entry.getKey(), entry.getValue()))
    .toList();
Related