Java 8 flatMap example
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的更多相关文章
- Java 8-Lambda表达式、方法引用、标准函数接口与流操作、管道操作之间的关系
1.Lambda表达式与接口之间的关系 只要Lambda表达式的声明形式与接口相一致,在很多情况下都可以替换接口.见如下代码 Thread t1 = new Thread(new Runnable() ...
- Reactor系列(七)flatMap映射
#java##reactor##flatMap# 视频讲解: https://www.bilibili.com/video/av79582009/ FluxMonoTestCase.java pack ...
- Spark问题记录
Spark 多线程时的序列化问题 临时记录 Exception in thread "Thread-28" org.apache.spark.SparkException: Ta ...
- Storm入门(十四)Trident API Overview
The core data model in Trident is the "Stream", processed as a series of batches. A stream ...
- JavaSE | Lambda| Optional| Stream API
JDK1.8新特性 1.接口:默认方法. 静态方法 2.Lambda表达式和StreamAPI 3.Optional类 4.新的日期时间API Lambda表达式:为了简化代码,使得Java支持 St ...
- Java8 stream学习
Java8初体验(二)Stream语法详解 Java 8 flatMap示例 第一个Stream Demo IDEA里面写Stream有个坑 虽然java文件中没错,但是但编译的时候还是报错了, In ...
- flink中使用lambda表达式
flink中使用lambda表达式 1.使用lambda的一个示例 2.使用上面这种写法通常或得到如下错误 3.解决方案 4.建议 5.完整代码 在 java8中有一种新的语法糖,即 lambda表达 ...
- Spark案例分析
一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...
- (八)map,filter,flatMap算子-Java&Python版Spark
map,filter,flatMap算子 视频教程: 1.优酷 2.YouTube 1.map map是将源JavaRDD的一个一个元素的传入call方法,并经过算法后一个一个的返回从而生成一个新的J ...
随机推荐
- 【linux】ubuntu中上下左右键变为^[[A^[[B^[[D^[[C问题处理
问题现象: 使用上下左右键时,结果为 ^[[A^[[B^[[D^[[C,如图: 原因在于ubuntu系统自带的 vi 不完整导致. 解决方法:安装完整的vi $ sudo apt-get instal ...
- JAVA的堆于栈
1. 栈(stack)与堆(heap):都是Java用来在Ram中存放数据的地方.与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆. 2. 栈的优势:存取速度比堆要快,仅次于直接位于C ...
- SQL Server查看被锁的表 - dead lock
select str(request_session_id ,4 ,0) as SPID ,convert(varchar(20) ,db_name(resource_database_id)) as ...
- go1.8之安装配置
说明: 之前学习过go语言(大概是0.9版本),后来更新太快,也没怎么使用,就荒废掉了,今年有项目需要用go开发,重新捡起. 这是我在学习go语言过程中整理的内容,这里记录下,也方便我以后查阅. 操作 ...
- Openwrt15.05网关后pptp外拨失败的解决办法
路由器升级openwrt chaos_calmer 15.05版后发现NAT后面的客户端外拨pptp vpn服务器失败,经google后得知,在14.07版本中默认安装的又一个叫做 kmod-ipt- ...
- MVC5为WebAPI添加命名空间的支持1
前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...
- 关于继承中的super()调用父类构造方法
super super可以理解为是指向自己超(父)类对象的一个指针,而这个超类指的是离自己最近的一个父类. 每当你new一个子类对象的时候,子类对象都隐式内置了一个父类对象.所以说,为了那个内置的父类 ...
- ssh无法登录,提示Pseudo-terminal will not be allocated because stdin is not a terminal.
当远程通过ssh登录主机时出现Pseudo-terminal will not be allocated because stdin is not a terminal. 错误 字面意思是伪终端将 ...
- Mac OS X上安装配置apache服务器
说明:Mac在安装完成Mac系统的时候它已经自带了apache服务器,接下来就是配置和将它启动运行了.那么接下来要做的事情就是: 1.配置apache的配置文件 2.设置虚拟主机 启动并查看apach ...
- spring配置详解-连接池配置
2010-08-27 一.连接池概述 数据库连接池概述: 数据库连接是一种关键的有限的昂贵的资源,这一点在多用户的网页应用程序中体现得尤为突出.对数据库连接的管理能显著影响到整个 应用程序的伸缩性和 ...