Nested ArrayList to single dimension

Spedwards :

I have some code that looks like this.

class A {}
class B extends A {
    private String name; // assume there's a getter
}
class C extends A {
    private List<B> items = new ArrayList<>(); // assume a getter
}

In another class, I have an ArrayList (ArrayList<A>). I'm trying to map this list to get all the names.

List<A> list = new ArrayList<>();
// a while later
list.stream()
    .map(a -> {
        if (a instanceof B) {
            return ((B) a).getName();
        } else {
            C c = (C) a;
            return c.getItems().stream()
                .map(o::getName);
        }
    })
    ...

The problem here is that I end up with something like this (JSON for visual purposes).

["name", "someName", ["other name", "you get the idea"], "another name"]

How can I map this list so I end up with the following as my result?

["name", "someName", "other name", "you get the idea", "another name"]
Eran :

Use flatMap:

list.stream()
    .flatMap(a -> {
        if (a instanceof B) {
            return Stream.of(((B) a).getName());
        } else {
            C c = (C) a;
            return c.getItems().stream().map(o::getName);
        }
    })
    ...

This will produce a Stream<String> of all the names, without nesting.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131727&siteId=1