java8之数据流Stream的Map和flatMap的区别

 XML Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.lyzx.day03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import org.junit.Test;

/**
 * 复习一下Map和flatMap
 * 关于Map和flatMap的区别
 * /
public class T1 {
    private static List  words = Arrays.asList( "hello world",
                                                        "hello java",
                                                        "hello hello");
    private static List  wordList = Arrays.asList( "aa", "bb", "cc");
    
    @Test
    public void test1(){
        words.stream()
              //对words的每一项都做切割操作,把每一个字符串都转换为数组
              //执行完后数据结构如下{[ "hello", "world"],[ "hello", "java"],[ "hello", "hello"]}
             .map(item - > item.split( " "))
              //对每个数组做单独的遍历操作
             .forEach(arr- >{
                 for(String item : arr){
                     System.out.println(item);
                 }
             });
    }
    
    @Test
    public void test2(){
        words.stream()
              //把每一项转化为数组包含列表的Stream流
              //然后这个函数把所有的List里面的字符串都取出来放在了一个集合中,这个集合做下一次执行的数据源
              //{ "hello", "world", "hello", "java", "hello", "hello"}
             .flatMap(item- >{
                 String[] arr = item.split( " ");
                 return Arrays.asList(arr).stream();
             })
              //根据每一项的HashCode和equals方法做去重操作
             .distinct()
              //打印每一项
             .forEach(item- >System.out.println(item));
    }
    
    @Test
    public void test3(){
        wordList.stream()
                 //把T1的getCharacter方法应用于wordList的每一项,wordList每一项都是String
                 //getCharacter方法的参数也是String,符合函数式接口
                 //通过map方法就把wordList的每一项都转换为了存放单个字符(以字符串的形式存放)列表的Stream流即Stream <List >
                .map(T1::getCharacter)
                 //对转换后的每一项(List)分别做遍历操作
                .forEach(sm- >{
                    sm.forEach(System.out::println);
                });
    }
    
    @Test
    public void test4(){
        wordList.stream()
                .flatMap(T1::getCharacter)
                .distinct()
                .forEach(System.out::println);
    }
    
    public static Stream  getCharacter(String str){
        char[] array = str.toCharArray();
        List  list = new ArrayList ();
        
        for(char item : array){
            list.add(String.valueOf(item));
        }
        Stream  stream = list.stream();
        return stream;
    }
}

你可能感兴趣的:(java8之数据流Stream的Map和flatMap的区别)