转载 

Java 8 flatMap example

分类:    222人阅读    IT小君  2018-07-01 09:41

In Java 8, Stream can hold different data types, for examples:


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

But, the Stream operations (filter, sum, distinct…) and collectors do not support it, so, we need flatMap() to do the following conversion :


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

How flatMap() works :

{ {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'}

1. Stream + String[] + flatMap

1.1 The below example will print an empty result, because filter() has no idea how to filter a stream of 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<String[]>
        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

//empty...

1.2 In above example, we should use flatMap() to convert Stream<String[]> to Stream<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<String[]>
        Stream<String[]> temp = Arrays.stream(data);

        //Stream<String>, 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<String> stream = Arrays.stream(data)
                .flatMap(x -> Arrays.stream(x))
                .filter(x -> "a".equals(x.toString()));*/

    }

}

Output

a

2. Stream + Set + flatMap

2.1 A student 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() and Set example.

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<Set<String>>
                        .flatMap(x -> x.stream())   //Stream<String>
                        .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

Try comments the flatMap(x -> x.stream()) the Collectors.toList() will prompts a compiler error, because it has no idea how to collect a stream of Set object.

3. Stream + Primitive + flatMapToInt

3.1 For primitive type, you can use 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<int[]>
        Stream<int[]> streamArray = Stream.of(intArray);

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

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

    }

}

Output

1
2
3
4
5
6

References

  1. Stream#flatMap JavaDoc
  2. Stackoverflow – Difference between map and flatMap methods in Java 8
  3. Java 8 – How to print an Array
  4. Java 8 – Collectors groupingBy and mapping example
点击广告,支持我们为你提供更好的服务

有机水果蔬菜HTML5网站模板

网页设计开发公司网站模板

html5 canvas彩色碎片组合球形旋转动画特效

js+css3抽奖转盘旋转点餐代码

css鼠标跟随文字模糊特效

html5图标下拉搜索框自动匹配代码

HTML5数字产品服务公司网站模板

现代时尚家具公司网站模板

HTML5现代家居装潢公司网站模板

html5 canvas进度条圆环图表统计动画特效

响应式太阳能能源公司网站模板

canvas炫酷鼠标移动文字粒子特效

jQuery右端悬浮带返回顶部特效

中小型创意设计服务公司网站模板

小众时尚单品在线电子商务网站模板

HTML5 Canvas竖直流动线条背景动画特效

响应式时尚单品在线商城网站模板

css+js实现的颜色渐变数字时钟动画特效

响应式咖啡饮品宣传网站模板

html5 svg夜空中星星流星动画场景特效

点击广告,支持我们为你提供更好的服务
 工具推荐 更多»
点击广告,支持我们为你提供更好的服务