Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the java 8 equivalent to Guava's transformAndConcat?

Tags:

java

java-8

guava

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?

like image 251
Fritz Duchardt Avatar asked Jul 15 '15 13:07

Fritz Duchardt


1 Answers

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

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

like image 126
user158037 Avatar answered Oct 13 '22 22:10

user158037