Search code examples
javajava-stream

Convert a Map<String, List<Object>> to Map<String, List<ClassVariable>> using java streams


I have a class example:

class Test {
     String id;
     int a;
     TestObject1[] someObjectArray;
     TestObject2[] someOtherObjectArray;
}

I have a map of Map<String, List<Test>> where String is "id". I need to convert these to Map<String, List<someObjectArray>> and Map<String, List<someOtherObjectArray>> using streams.

Tried something like this but couldn't get anywhere.

HashMap<String, List<Test>> map =
        map.entrySet().forEach( p -> map.computeIfAbsent(p, k -> 
               new ArrayList<>())).add(p);

Solution

  • Map<String, List<Test>> initialMap = new HashMap<>();
    
    Map<String, List<TestObject1>> firstMap = initialMap.entrySet()
        .stream()
        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue()
                    .stream()
                    .flatMap(test -> Arrays.stream(test.getSomeObjectArray()))
                    .toList()
            )
        );
    
    Map<String, List<TestObject2>> secondMap = initialMap.entrySet()
        .stream()
        .collect(
            Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue()
                    .stream()
                    .flatMap(test -> Arrays.stream(test.getSomeOtherObjectArray()))
                    .toList()
            )
        );
    

    }

    if .toList() is not resolving on the inner stream you can use .collect(Collectors.toList()) instead.

    Also, if you're expecting to process huge amount of data in such way it is really would be better for performance to use for loop