Java代码信息

运行结果
教程手册
代码仓库
点击编辑器上方的运行按钮,会在此处显示运行结果。
以下是用户最新保存的代码
主函数-- 发布于:2020-08-10 17:17 主函数-- 发布于:2020-08-10 17:16 主函数-- 发布于:2020-08-10 17:16 定义类-学生-继承自人类 发布于:2020-08-10 17:11 自动截取日本名称 发布于:2020-08-08 12:10 Base64 发布于:2020-08-07 14:37 池塘问题,待修改 发布于:2020-08-10 14:36 自动截取日本名称 发布于:2020-08-08 11:57 API random (摇塞子游戏) 发布于:2020-08-06 15:05 Nginx log escape 发布于:2020-08-07 15:55 《算法》练习1.1.6 发布于:2020-08-04 21:29 排序... 发布于:2020-08-04 22:10 斐波那契函数 发布于:2020-08-04 15:37 《算法》练习1.1.5 发布于:2020-08-03 23:41 《算法》练习1.1.3 发布于:2020-08-03 22:13 《算法》练习1.1.2 发布于:2020-08-03 20:37 《算法》练习1.1.1 发布于:2020-08-03 19:24 jvaaaaa 发布于:2020-08-03 14:16 练习加深印象 发布于:2020-08-03 13:54 测试显目1 发布于:2020-07-31 16:20 hh-test 发布于:2020-07-30 10:28 聊天小工具。 发布于:2020-07-30 09:40 使用for循环嵌套实现99乘法表。 发布于:2020-07-29 21:22 for循环嵌套练习。 发布于:2020-07-29 19:55 加深三目运算符练习。 发布于:2020-07-29 13:50 逻辑运算符加深印象。 发布于:2020-07-29 13:38 写着玩的东西 发布于:2020-07-30 11:26 算算舍罕王给了多少粒麦子 发布于:2020-07-27 22:48 leetcode 发布于:2020-07-27 01:29 java练习输出打印1到100的奇数和偶数。 发布于:2020-07-25 15:03 test1 发布于:2020-07-24 14:16 第三届天命杯Roll图/模式 发布于:2020-07-23 20:17 用if和else循环判断是雨天还是睛天,男女的状态 发布于:2020-07-23 18:23 用switch循环判断男女还有天气 发布于:2020-07-23 18:22 用switch循环判断输入的数值是星期几。 发布于:2020-07-23 18:22 这个源码是表示商场打折判断写法 发布于:2020-07-23 18:21 这个源码是写用if判断成绩的 发布于:2020-07-23 18:19 用来正实是否是质数的写法 发布于:2020-07-23 18:17 一个登陆功能小文本 发布于:2020-07-23 18:15 用一个递归和一个for循环来表示两个数据 发布于:2020-07-23 18:13 java豪宅房租计算脚本 发布于:2020-07-23 17:49 java练习 发布于:2020-07-23 16:28 输出语句,是System.out.println的... 发布于:2020-07-23 10:27 测试三元运算符 发布于:2020-07-22 19:35 【基础】-数据结构 发布于:2020-07-23 22:40 测试数据类型之间的自动转换和强制转换 发布于:2020-07-22 10:32 java Queue 应用,先进先出用法实例, ... 发布于:2020-07-21 17:16 服务器代码 发布于:2020-07-20 10:59 客户端代码 发布于:2020-07-20 11:53 [更多]
显示目录

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

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
由JSRUN为你提供的Java在线工具
        JSRUN提供的Java在线运行,Java 在线编译工具,基于linux操作系统环境提供线上编译和线上运行,具有运行快速,运行结果与常用开发、生产环境保持一致的特点。

title

使用此草稿 删除草稿