Java 8 flatMap示例

在Java 8中,Stream可以容纳不同的数据类型,例如:

Stream<String[]>
Stream<Set<String>>
Stream<List<String>>
Stream<List<Object>>

但是,Stream操作(filter,sum,distinct ...)和collectors不支持它,所以我们需要使用flatMap()进行以下转换:

Stream<String[]>		-> flatMap ->	Stream<String>
Stream<Set<String>>	-> flatMap ->	Stream<String>
Stream<List<String>>	-> flatMap ->	Stream<String>
Stream<List<Object>>	-> flatMap ->	Stream<Object>

如何flatMap()工作:

{{1,2},{3,4},{5,6}}  - > flatMap  - > {1,2,3,4,5,6}

{'a','b'},{'c','d'},{'e','f'}}  - > flatMap  - > {'a','b','c' D”, 'E', 'F'}

Stream + String [] + flatMap

1.1以下示例将打印一个空的结果,因为filter()不知道如何过滤流String[]

TestExample1.java
package com.mkyong.java8;

import java.util.Arrays;
import java.util.stream.Stream;

public class TestExample1 {

    public static void main(String[] args) {

        String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};

        //Stream
        Stream<String[]> temp = Arrays.stream(data);

        //filter a stream of string[], and return a string[]?
        Stream<String[]> stream = temp.filter(x -> "a".equals(x.toString()));

        stream.forEach(System.out::println);

    }

}

Output

//空...

1.2在上面的例子中,我们应该使用flatMap()转换StreamStream

TestExample1.java
package com.mkyong.java8;

import java.util.Arrays;
import java.util.stream.Stream;

public class TestExample1 {

    public static void main(String[] args) {

        String[][] data = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}};

        //Stream
        Stream<String[]> temp = Arrays.stream(data);

        //Stream, GOOD!
        Stream<String> stringStream = temp.flatMap(x -> Arrays.stream(x));

        Stream<String> stream = stringStream.filter(x -> "a".equals(x.toString()));

        stream.forEach(System.out::println);

		/*Stream stream = Arrays.stream(data)
                .flatMap(x -> Arrays.stream(x))
                .filter(x -> "a".equals(x.toString()));*/

    }

}

Output

a

Stream + Set + flatMap

2.1学生POJO。

Student.java
package com.mkyong.java8;

import java.util.HashSet;
import java.util.Set;

public class Student {

    private String name;
    private Set<String> book;

    public void addBook(String book) {
        if (this.book == null) {
            this.book = new HashSet<>();
        }
        this.book.add(book);
    }
    //getters and setters

}

2.2 flatMap()Set例子。

TestExample2.java
package com.mkyong.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TestExample2 {

    public static void main(String[] args) {

        Student obj1 = new Student();
        obj1.setName("mkyong");
        obj1.addBook("Java 8 in Action");
        obj1.addBook("Spring Boot in Action");
        obj1.addBook("Effective Java (2nd Edition)");

        Student obj2 = new Student();
        obj2.setName("zilap");
        obj2.addBook("Learning Python, 5th Edition");
        obj2.addBook("Effective Java (2nd Edition)");

        List<Student> list = new ArrayList<>();
        list.add(obj1);
        list.add(obj2);

        List<String> collect =
                list.stream()
                        .map(x -> x.getBook())      //Stream>
                        .flatMap(x -> x.stream())   //Stream
                        .distinct()
                        .collect(Collectors.toList());

        collect.forEach(x -> System.out.println(x));
    }

}

Output

Spring Boot in Action
Effective Java (2nd Edition)
Java 8 in Action
Learning Python, 5th Edition
尝试评论 flatMap(x -> x.stream()) Collectors.toList() 会出现提示编译器错误,因为它不知道如何收集组对象的流。

Stream + Primitive + flatMapToInt

3.1对于原始类型,可以使用flatMapToInt

TestExample3.java
package com.mkyong.java8;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class TestExample3 {

    public static void main(String[] args) {

        int[] intArray = {1, 2, 3, 4, 5, 6};

        //1. Stream
        Stream<int[]> streamArray = Stream.of(intArray);

        //2. Stream -> flatMap -> IntStream
        IntStream intStream = streamArray.flatMapToInt(x -> Arrays.stream(x));

        intStream.forEach(x -> System.out.println(x));

    }

}

Output

1 
2 
3 
4 
5 
6

你可能感兴趣的:(JDK8,JDK8,lambda表达式,java8)