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?
我的问题是如何用Java 8流API实现相同的目标?
1 个解决方案
#1
13
List<String> allString = holders.stream()
.flatMap(h -> h.getList().stream())
.collect(Collectors.toList());
Here is an older question about collection flattening: (Flattening a collection)
这是一个关于收集扁平化的老问题:(压扁一个集合)
#1
13
List<String> allString = holders.stream()
.flatMap(h -> h.getList().stream())
.collect(Collectors.toList());
Here is an older question about collection flattening: (Flattening a collection)
这是一个关于收集扁平化的老问题:(压扁一个集合)