Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 733
Yan Khonski Avatar asked Feb 03 '19 15:02

Yan Khonski


People also ask

How to flatten nested lists in Java?

List<Integer> flatList = new ArrayList<>(); listOfLists. forEach(flatList::addAll); For each list in the nested list, we'll add all the elements into the flatList . This is a concise solution that avoids the Stream API altogether.

How to flatten a set of sets Java?

Stream flatMap() method is used to flatten a Stream of collections to a stream of objects. The objects are combined from all the collections in the original stream. The flatMap() method is a one-to-many transformation to the elements of the stream and then flattening the resulting elements into a new stream.

How do you flatten a stream List?

The standard solution is to use the Stream. flatMap() method to flatten a List of Lists. The flatMap() method applies the specified mapping function to each element of the stream and flattens it.


2 Answers

class Loop {
    private static Stream<Object> flat(Object o) {
        return o instanceof Collection ?
                ((Collection) o).stream().flatMap(Loop::flat) : Stream.of(o);
    }

    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> flat = flat(objects).collect(Collectors.toList());

        System.out.println(flat);
    }
}

Please note List.of(null) throws NPE.

like image 143
Adam Siemion Avatar answered Sep 21 '22 05:09

Adam Siemion


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);
}
like image 28
Fullstack Guy Avatar answered Sep 18 '22 05:09

Fullstack Guy