Java 8 flatMap example

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

http://www.mkyong.com/java8/java-8-flatmap-example/

Java 8 flatMap example的更多相关文章

  1. Java 8-Lambda表达式、方法引用、标准函数接口与流操作、管道操作之间的关系

    1.Lambda表达式与接口之间的关系 只要Lambda表达式的声明形式与接口相一致,在很多情况下都可以替换接口.见如下代码 Thread t1 = new Thread(new Runnable() ...

  2. Reactor系列(七)flatMap映射

    #java##reactor##flatMap# 视频讲解: https://www.bilibili.com/video/av79582009/ FluxMonoTestCase.java pack ...

  3. Spark问题记录

    Spark 多线程时的序列化问题  临时记录 Exception in thread "Thread-28" org.apache.spark.SparkException: Ta ...

  4. Storm入门(十四)Trident API Overview

    The core data model in Trident is the "Stream", processed as a series of batches. A stream ...

  5. JavaSE | Lambda| Optional| Stream API

    JDK1.8新特性 1.接口:默认方法. 静态方法 2.Lambda表达式和StreamAPI 3.Optional类 4.新的日期时间API Lambda表达式:为了简化代码,使得Java支持 St ...

  6. Java8 stream学习

    Java8初体验(二)Stream语法详解 Java 8 flatMap示例 第一个Stream Demo IDEA里面写Stream有个坑 虽然java文件中没错,但是但编译的时候还是报错了, In ...

  7. flink中使用lambda表达式

    flink中使用lambda表达式 1.使用lambda的一个示例 2.使用上面这种写法通常或得到如下错误 3.解决方案 4.建议 5.完整代码 在 java8中有一种新的语法糖,即 lambda表达 ...

  8. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  9. (八)map,filter,flatMap算子-Java&Python版Spark

    map,filter,flatMap算子 视频教程: 1.优酷 2.YouTube 1.map map是将源JavaRDD的一个一个元素的传入call方法,并经过算法后一个一个的返回从而生成一个新的J ...

随机推荐

  1. spring Ioc 实践

    了解过IoC的概念,没有真正实践,感觉还是会比较模糊.自己的实践虽然简单,但还是记录下呀~ 1. 通过注解的方式注入service 1.1 controller中创建对象 @Controller @R ...

  2. Android ART runtime简述

    此文章原始是PPT格式已转换为PDF,完整内容也能够下载文档阅读: AndroidARTruntimeOverview watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5 ...

  3. selenium快速跳转视图到指定元素

    首先判断元素是否存在,如果存在的时候使用location_once_scrolled_into_view就可以滚动到某个元素处,也就是滚动直到这个元素出现在屏幕里.

  4. js 内置函数 内置对象

    1.内置函数 Object Array Boolean Number String Function Date RegExp Error 2.内置对象 Date JSON

  5. ES6学习笔记十:模块的导入、导出

    一:模块导入 1) import { 要导入的属性.方法民 } from '模块路径'; 2)该种方法需要有配置文件,指明模块所在路径 import { 要导入的属性.方法民 } from '模块名' ...

  6. ES5学习笔记

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/7234053.html 一:基础 1:语法 ECMAScript 中的变量无特定的类型,定义变量时只用 var ...

  7. Red Hat7.2 上安装 MySQL5.5.58

    1.首先查看linux版本:cat /etc/redhat-release Red Hat Enterprise Linux Server release 7.2 (Maipo) 2.Linux查看版 ...

  8. Spring MVC测试框架详解——服务端测试

    随着RESTful Web Service的流行,测试对外的Service是否满足期望也变的必要的.从Spring 3.2开始Spring了Spring Web测试框架,如果版本低于3.2,请使用sp ...

  9. SpringMVC multipart文件上传

    一.介绍   spring内建的multipart支持网络程序文件上传.我们可以通过配置MultipartResolver来启动上传支持.它定义在org.springframework.web.mul ...

  10. NFC手机上基于软件的卡模拟 重大利好还是安全噩梦?(转)

    Software Card Emulation in NFC-enabled Mobile Phones: GreatAdvantage or Security Nightmare? Michael ...