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. 微信小程序 - 图片懒加载

    wxml <!-- 数据源 --> <view class='item-{{index}}' wx:for="{{lazyData}}" wx:key=" ...

  2. OpenERP 7中 openerp-server.conf 的解释

    服务器启动配置 – 通用项 程序代码: [选择] # Admin password for creating, restoring and backing up databases admin_pas ...

  3. 〖Linux〗上传单个文件到FTP的Shell命令行(函数)

    #!/bin/bash - #=============================================================================== # # F ...

  4. 一次dns缓存引发的慘案

    时间2015年的某个周六凌晨5点,公司官方的QQ群实用户反馈官网打不开了,但有的用户反馈能够打开.客服爬起来自己用电脑试了一下没有问题,就给客户反馈说.可能是自己网络的问题,请过会在试试.早点8点,越 ...

  5. log4j的详细配置(最省心完美配置)

    先说下我的需求 1,可以记录日记在我们的java开发项目周期中: 2,很简单即可输出日志: 3,每天按照时间将不同的日志输出到不同的文件中,每天输出日志到一个带有当前时间戳的文件中: 4,可以修改当前 ...

  6. V-rep学习笔记:外部函数调用方式

    The remote API functions are interacting with V-REP via socket communication in a way that reduces l ...

  7. adb shell中的am pm命令

    adb shell中的am pm命令,一些自己的见解和大多数官网的翻译. am命令 am全称activity manager,你能使用am去模拟各种系统的行为,例如去启动一个activity,强制停止 ...

  8. 修改mysql数据引擎的方法- 提高数据库性能

    前言:同学告我说,他为了能使得数据查询变得快一点,修改的数据引擎,故查询一下,总结一下. 登录mysql后,查看当前数据库支持的引擎和默认的数据库引擎,使用下面命令: mysql>show en ...

  9. 网页屏蔽Backspace事件,输入框不屏蔽

    document.onkeydown = function (e) { var code; if (!e){ var e = window.event;} if (e.keyCode){ code = ...

  10. 使用CodePush实时更新 React Native 和 Cordova 应用

    近期公司的React native App(云订货)用上CodePush实时更新App技术了.棒棒的 CodePush 是微软开发的.能够实时更新 React Native 和 Cordova 应用. ...