java8-flatMap

/**
 * flatMap
 */
public static void flatMapString() {
    List<PersonModel> data = Data.getData();
    //返回类型不一样
    List<String> list = data.stream()
            .flatMap(personModel -> Arrays.stream(personModel.getName().split("")))
            .collect(Collectors.toList());

    List<Stream<String>> collect = data.stream()
            .map(personModel -> Arrays.stream(personModel.getName().split("")))
            .collect(Collectors.toList());

    //用map实现
    List<String> collect1 = data.stream()
            .map(personModel -> personModel.getName().split(""))
            .flatMap(Arrays::stream)
            .collect(Collectors.toList());

    //另一种方式实现
    List<String> collect2 = data.stream()
            .map(personModel -> personModel.getName().split(""))
            .flatMap(str -> Arrays.asList(str).stream())
            .collect(Collectors.toList());
}

猜你喜欢

转载自blog.csdn.net/wb_zjp283121/article/details/89057283