使用flatMap处理Java中的嵌套集合

1.嵌套集合的示例

List<List<String>> nestedList = asList(
  asList("one:one"), 
  asList("two:one", "two:two", "two:three"), 
  asList("three:one", "three:two", "three:three", "three:four"));

2.使用forEach整合列表

为了将这个嵌套的集合展平为字符串列表,可以将forEach与Java 8方法参考结合使用:

public <T> List<T> flattenListOfListsImperatively(
    List<List<T>> nestedList) {
    
    
    List<T> ls = new ArrayList<>();
    nestedList.forEach(ls::addAll);
    return ls;
}
@Test
public void test7() {
    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"));
}

3.使用flatMap展平列表

可以利用Stream API中的flatMap方法展平嵌套列表。

可以展平嵌套的Stream结构,并最终将所有元素收集到一个特定的集合中:

public <T> List<T> flattenListOfListsStream(List<List<T>> list) {
    
    
    return list.stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toList());    
}
 @Test
    public void test8() {
    
    
        List<String> ls = flattenListOfListsStream(nestedList);
        System.out.println(ls);
        assertNotNull(ls);
        assertTrue(ls.size() == 8);
    }

猜你喜欢

转载自blog.csdn.net/niugang0920/article/details/115358837