6

Lets assume I have a class containing a List, e.g.

 public static class ListHolder {
    List<String> list = new ArrayList<>();

    public ListHolder(final List<String> list) {
        this.list = list;
    }

    public List<String> getList() {
        return list;
    }
}

Let's furthermore assume I have a whole list of instances of this class:

    ListHolder listHolder1 = new ListHolder(Arrays.asList("String 1", "String 2"));
    ListHolder listHolder2 = new ListHolder(Arrays.asList("String 3", "String 4"));
    List<ListHolder> holders = Arrays.asList(listHolder1, listHolder2);

And now I need to extract all Strings to get a String List containing all Strings of all instances, e.g.:

[String 1, String 2, String 3, String 4]

With Guava this would look like this:

     List<String> allString = FluentIterable
            .from(holders)
            .transformAndConcat(
                    new Function<ListHolder, List<String>>() {
                        @Override
                        public List<String> apply(final ListHolder listHolder) {
                            return listHolder.getList();
                        }
                    }
            ).toList();

My question is how can I achieve the same with the Java 8 stream API?

Fritz Duchardt
  • 11,026
  • 4
  • 41
  • 60

1 Answers1

15
List<String> allString = holders.stream()
    .flatMap(h -> h.getList().stream())
    .collect(Collectors.toList());

Here is an older question about collection flattening: (Flattening a collection)

Community
  • 1
  • 1
user158037
  • 2,659
  • 1
  • 24
  • 27