Skip to content
Advertisement

Flatmap nested collection

I have a list of objects, some of them can be collections. I would like to get a stream of plain objects.

List<Object> objects = List.of(1, 2, "SomeString", List.of(3, 4, 5, 6), 
    7, List.of("a", "b", "c"),
    List.of(8, List.of(9, List.of(10))));

I would like to get a stream with elements.

1, 2, "SomeString", 3, 4, 5, 6, 7, "a", "b", "c", 8, 9, 10

I have tried

Function<Object, Stream<Object>> mbjectToStreamMapper = null; //define it. I have not figured it out yet!
objects.stream().flatMap(ObjectToStreamMapper).forEach(System.out::println);

I also checked an example which shows how to use a recursive function which flattens a collection. However, in this example .collect(Collectors.toList()); used to keep an intermediate result. Collectors.toList() is a terminal operation, which will start processing the stream right away. I would like to get a stream, which I can iterate on later.


Update

I agree with comments, it is a terrible idea to have a stream composed of objects of different nature. I just wrote this question for simplicity. In real life, it can be that I listen to different events, and process some business objects from incoming streams, some of them can send stream of objects, other – just single objects.

Advertisement

Answer

We can recursively get the nested stream if the object being traversed is an instance of Collection.

public static void main(String args[]) {
       List<Object> objects = List.of(1, 2, "SomeString", List.of(3, 4, 5, 6),
            7, List.of("a", "b", "c"),
            List.of(8, List.of(9, List.of(10))));
       List<Object> list = objects.stream().flatMap(c -> getNestedStream(c)).collect(Collectors.toList());
}

public static Stream<Object> getNestedStream(Object obj) {
    if(obj instanceof Collection){
        return ((Collection)obj).stream().flatMap((coll) -> getNestedStream(coll));
    }
    return Stream.of(obj);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement