简体   繁体   中英

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

Lets assume I have a class containing a List , eg

 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, eg:

[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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM