1. Overview
1.概述
In this quick article, we’ll explore how to flatten a nested collection in Java.
在这篇快速文章中,我们将探讨如何在Java中平铺一个嵌套的集合。
2. Example of a Nested Collection
2.嵌套集合的例子
Suppose we have a list of lists of type String.
假设我们有一个类型为String的列表。
List<List<String>> nestedList = asList(
asList("one:one"),
asList("two:one", "two:two", "two:three"),
asList("three:one", "three:two", "three:three", "three:four"));
3. Flattening the List With forEach
3.用forEach扁平化列表
In order to flatten this nested collection into a list of strings, we can use forEach together with a Java 8 method reference:
为了将这个嵌套的集合平铺成一个字符串的列表,我们可以使用forEach和Java 8方法引用。
public <T> List<T> flattenListOfListsImperatively(
List<List<T>> nestedList) {
List<T> ls = new ArrayList<>();
nestedList.forEach(ls::addAll);
return ls;
}
And here you can see the method in action:
而在这里,你可以看到该方法的实际应用。
@Test
public void givenNestedList_thenFlattenImperatively() {
List<String> ls = flattenListOfListsImperatively(nestedList);
assertNotNull(ls);
assertTrue(ls.size() == 8);
assertThat(ls, IsIterableContainingInOrder.contains(
"one:one",
"two:one", "two:two", "two:three", "three:one",
"three:two", "three:three", "three:four"));
}
4. Flattening the List With flatMap
4.用flatMap对List进行扁平化
We can also flatten the nested list by utilizing the flatMap method from the Stream API.
我们还可以通过利用Stream API中的flatMap方法来平整嵌套的列表。
This allows us to flatten the nested Stream structure and eventually collect all elements to a particular collection:
这使得我们可以将嵌套的Stream结构扁平化,并最终将所有元素收集到一个特定的集合。
public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
return list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
And here’s the logic in action:
下面是这个逻辑的作用。
@Test
public void givenNestedList_thenFlattenFunctionally() {
List<String> ls = flattenListOfListsStream(nestedList);
assertNotNull(ls);
assertTrue(ls.size() == 8);
}
5. Conclusion
5.结论
A simple forEach or flatMap methods in Java 8, in combination with method references, can be used for flattening nested collections.
Java 8中简单的forEach或flatMap方法,结合方法引用,可用于扁平化嵌套的集合。
You can find the code discussed in this article over on GitHub.
你可以在GitHub上找到本文讨论的代码。