Search code examples
javajava-8hashmapjava-stream

Iterating over a List of nested objects and storing them into a HashMap using Stream API


I am trying to iterate over nested java object and from nested object I'm trying to populate a map using Java 8.

Here is the list and structure of objects

IssueTypeDto.java

public class IssueTypeDto {
    private String id;
    private String name;
    private List<CustomFieldDto> customFields;
}

CustomFieldDto.java

    private String id;
    private TypeDto type;

I am getting List of IssueTypeDto as response. Each IssueTypeDto object can have a list of CustomFieldDto objects. My requirement is I need to iterate over a list of IssueTypeDto objects and for each CustomFieldDto object I need to get id and the corresponding TypeDto object and insert it into a map as key and value. Here is what I am trying to do currently

Map<String, TypeDto> map = issueTypes.stream()
    .flatMap(issueType->issueType.getCustomFields().stream()
                .collect(Collectors.toMap(
                            CustomFieldDto::getId,
                            CustomFieldDto::getType)));

But i am getting compile time error as Type mismatch:

cannot convert from Stream<Object> to Map<String,TypeDto>"

I am new to Java 8 streams. So I am not able to figure out the issue. Any help would be appreciated.


Solution

  • Let's know the general concepts. You want to transform one object to another one. It can be 1 to 1 relationship or 1 to many. In case of 1 to 1 you need to use .map. 1 to many - .flatMap. So in other words map convert Object A to Object B. flatMap convert Object A to Stream of Object B. You was near you missed ')'.

    Your case should be like this:

    issueTypes.stream()
    .flatMap(issueType -> issueType.getCustomFields().stream())
    .collect(Collectors.toMap(CustomFieldDto::getId CustomFieldDto::getType));
    

    Also please be sure that there are no duplicates on keys of different objects, otherwise Collectors.toMap() will throw exception due to key duplication.