# 拼合Java中的嵌套集合

## 2.嵌套集合的示例

``````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.使用forEach整理列表

``````public <T> List<T> flattenListOfListsImperatively(

List<List<T>> nestedList) {

List<T> ls = new ArrayList<>();

return ls;

}
``````

``````@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.使用flatMap展平列表

``````public <T> List<T> flattenListOfListsStream(List<List<T>> list) {

return list.stream()

.flatMap(Collection::stream)

.collect(Collectors.toList());

}
``````

``````@Test

public void givenNestedList_thenFlattenFunctionally() {

List<String> ls = flattenListOfListsStream(nestedList);

assertNotNull(ls);

assertTrue(ls.size() == 8);

}``````

## 5.結論

Java 8中簡單的forEach或flatMap方法與方法引用結合使用，可以使嵌套集合變平坦。