Flatmap nested collection

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);
}

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.


Note, it's possible to define recursive methods in a field:

public class Test {
  static Function<Object,Stream<?>> flat=
    s->s instanceof Collection ? ((Collection<?>)s).stream().flatMap(Test.flat) : Stream.of(s);
  public static void main(String[] args) {
    objects.stream().flatMap(flat).forEach(System.out::print);
  }
}