java8的stream流练习-3 flatMap的使用

// flatMap 拉平多个流为一个
        List a=new ArrayList<>();
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(2);
        List b=new ArrayList<>();
        b.add(3);
        b.add(4);
        b.add(5);
        
        Stream.of(a, b);
        
        List newList = Stream.of(a, b).flatMap(u -> u.stream()).distinct().sorted().collect(Collectors.toList());
        System.out.println(newList); // [1, 2, 3, 4, 5]

flatMap另外一例子:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @Author weijun.nie
 * @Date 2020/6/22 11:31
 * @Version 1.0
 */
public class Test {

    public static void main(String[] args) {
        // A: 第一种
        List xList = Arrays.asList(1, 3, 5, 7);
        List yList = Arrays.asList(2, 4, 6, 8, 10);

        List collect = xList.stream().
                flatMap(
                        i -> yList.stream()
                                .map(j -> new int[]{i, j})
                )
                .collect(Collectors.toList());
        collect.stream()
                .forEach(a -> System.out.println("(" + a[0] + ", " + a[1] + ")"));


        // B:第二种
        int[] xArr = {1, 3, 5, 7};
        int[] yArr = {2, 4, 6, 8, 10};
        List intsList = Arrays.stream(xArr).boxed()
                .flatMap(i -> Arrays.stream(yArr).boxed()
                        .map(j -> new int[]{i, j})
                )
                .collect(Collectors.toList());

        intsList.stream().forEach(a -> System.out.println("(" + a[0] + "," + a[1] + ")"));
    }
}

两种A/B都可以输出如下: 需要注意的是: 需要装箱:
Arrays.stream(xArr).boxed()的 boxed
Arrays.stream(yArr).boxed()的 boxed

(1,2)
(1,4)
(1,6)
(1,8)
(1,10)
(3,2)
(3,4)
(3,6)
(3,8)
(3,10)
(5,2)
(5,4)
(5,6)
(5,8)
(5,10)
(7,2)
(7,4)
(7,6)
(7,8)
(7,10)

你可能感兴趣的:(java8,flatmap)