0%

java8-stream练习3-flatMap使用

1. flatMap

// flatMap 拉平多个流为一个
        List<Integer> a=new ArrayList<>();
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(2);
        List<Integer> b=new ArrayList<>();
        b.add(3);
        b.add(4);
        b.add(5);
        
        Stream.of(a, b);
        
        List<Integer> 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<Integer> xList = Arrays.asList(1, 3, 5, 7);
        List<Integer> yList = Arrays.asList(2, 4, 6, 8, 10);

        List<int[]> 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<int[]> 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] + ")"));
    }
}

2. boxed()

两种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)