• Java SE 8 流库(二)


    1.3. filter,map,flatMAP方法

    流的转换会产生一个新流,它的元素派生出自另一个流中的元素;

    Stream<T> filter(Predicate<? super T> predicate)   返回一个包含此流中与某种条件相匹配的流

    <R> Stream<R> map(Function<? super T,? extends R> mapper)  返回由将给定函数应用于此流的元素的结果组成的流。

    <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper) 返回一个流,该流包含将此流的每个元素替换为通过将所提供的映射函数应用于每个元素而生成的映射流的内容的结果。每个映射流在其内容被放置到这个流之后关闭(如果映射流为空,则使用空流)。

    1.3.1. filter方法

    Filter转换产生一个新流,它的元素与某种条件相匹配;

    1 String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    2         List<String> words = Arrays.asList(contents.split("\PL+"));
    3         //filter转换会产生一个流(值包含长单词的另一个流)
    4         Stream<String> newStream = words.stream()
    5                 .filter(w -> w.length() > 6);

    1.3.2. map方法

    在使用map时,会有一个函数应用到每个元素上,并且其结果包含了应用该函数后所产生的所有结果流;

    1 String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    2         List<String> words = Arrays.asList(contents.split("\PL+"));
    3        //map按照某种方式来转换流中的值
    4         Stream<String> mapStream = words.stream().map(String::toUpperCase);
    5         List<String> list = mapStream.limit(10)
    6                 .collect(Collectors.toList());
    7         for(int i=0;i<list.size();i++){
    8             System.out.println(list.get(i));
    9         }

    1.3.3. flatmap方法

     1 String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
     2         List<String> words = Arrays.asList(contents.split("\PL+"));
     3 Stream<String> result = words.stream()
     4                 .flatMap(w -> letters(w));
     5 show(result);
     6 
     7 public static Stream<String> letters(String s){
     8 
     9         ArrayList<String> result = new ArrayList<>();
    10         for(int i=0;i<s.length();i++){
    11             result.add(s.substring(i,i+1));
    12         }
    13         return result.stream();
    14     }
    15 
    16     public static <T> void show( Stream<T> stream){
    17         List<T> list = stream.limit(10)
    18                 .collect(Collectors.toList());
    19         for(int i=0;i<list.size();i++){
    20 
    21             System.out.println(list.get(i));
    22         }
    23     }

    1.4. 抽取子流和连接流

    Stream<T> limit(long maxSize)    返回由此流的元素组成的流,截断长度不超过maxSize。

    Stream<T> skip(long n)               丢弃流的前n个元素之后,返回由该流的其余元素组成的流。 如果这个流包含少于n个元素,那么将返回一个空的流。

    static <T> Stream<T> concat(Stream<? extends T> a,Stream<? extends T> b)   创建一个延迟连接的流,其元素是第一个流的所有元素,后跟第二个流的所有元素。 如果两个输入流都是有序的,则生成的流是有序的;如果任意一个输入流是并行的,则生成的流是并行的。 当结果流关闭时,调用两个输入流的关闭处理程序。

     1 /**
     2  * Created by Lenovo on 2017/12/18.
     3  * 抽取子流和链接流
     4  */
     5 public class Demo07 {
     6 
     7     private static final String filePath = "G:\Idea\src\com\itheima05\Test_JavaSE\Test_20171214\word.txt";
     8 
     9     public static void main(String[] args) throws Exception {
    10 
    11         String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    12         List<String> words = Arrays.asList(contents.split("\PL+"));
    13 
    14         //包含有10个随机数的流
    15         Stream<Double> random = Stream.generate(Math::random).limit(10);
    16         show(random);
    17 
    18         //split,丢弃前n个元素
    19         Stream<String> skip = words.stream().skip(5);
    20         show(skip);
    21 
    22         //concat将两个流连接起来
    23         Stream<String> concat = Stream.concat(letters("Hello"), letters("World"));
    24         show(concat);
    25     }
    26     public static <T> void show( Stream<T> stream){
    27         List<T> list = stream.limit(10)
    28                 .collect(Collectors.toList());
    29         for(int i=0;i<list.size();i++){
    30 
    31             System.out.println(list.get(i));
    32         }
    33     }
    34     public static Stream<String> letters(String s){
    35 
    36         ArrayList<String> result = new ArrayList<>();
    37         for(int i=0;i<s.length();i++){
    38             result.add(s.substring(i,i+1));
    39         }
    40         return result.stream();
    41     }
    42 }

    1.5. 其他流转换

    Stream<T> distinct()       返回由此流的不同元素(根据Object.equals(Object))组成的流。

    Stream<T> sorted()        返回由此流的元素组成的流,按照自然顺序排序。如果此流的元素不是Comparable,执行终端操作时可能会抛出java.lang.ClassCastException。

    Stream<T> peek(Consumer<? super T> action)   返回由此流的元素组成的流,另外对每个元素执行提供的操作,因为元素将从结果流中消耗。这是一个中间操作。

     1 /**
     2  * Created by Lenovo on 2017/12/18.
     3  * 其他转换流
     4  */
     5 public class Demo06 {
     6 
     7     public static void main(String[] args) {
     8 
     9         //将原有的流去重,获取一个新流
    10         Stream<String> distinct = Stream.of("aaa", "bbb", "ccc", "sss", "aaa").distinct();
    11         show(distinct);
    12 
    13         //sorted,倒序排序
    14         Stream<String> sorted = Stream.of("aaa", "aa", "aaaa", "a", "aaaaa")
    15                 .sorted(Comparator.comparing(String::length).reversed());
    16         show(sorted);
    17 
    18         //peek
    19         Object[] peek = Stream.iterate(1.0, p -> p * 2)
    20                 .peek(e -> System.out.println("fetching" + e))
    21                 .limit(20).toArray();
    22         for(int i = 0;i<peek.length;i++){
    23             System.out.println(peek[i]);
    24         }
    25     }
    26 
    27     public static <T> void show(Stream<T> stream){
    28         List<T> tList = stream.limit(10).collect(Collectors.toList());
    29         for(int i =0;i<tList.size();i++){
    30             System.out.println(tList.get(i));
    31         }
    32     }
    33 }

    结果输出:

     1 aaa
     2 bbb
     3 ccc
     4 sss
     5 aaaaa
     6 aaaa
     7 aaa
     8 aa
     9 a
    10 fetching1.0
    11 fetching2.0
    12 fetching4.0
    13 fetching8.0
    14 fetching16.0
    15 fetching32.0
    16 fetching64.0
    17 fetching128.0
    18 fetching256.0
    19 fetching512.0
    20 fetching1024.0
    21 fetching2048.0
    22 fetching4096.0
    23 fetching8192.0
    24 fetching16384.0
    25 fetching32768.0
    26 fetching65536.0
    27 fetching131072.0
    28 fetching262144.0
    29 fetching524288.0

    1.6.简单约简

    约简是一种终结操作,它们会将流约简为可以在程序中使用的非流值;

    例如:count,max,min都是简单约简,这些返回的是一个数据类型Optional<T>

    Optional<T> max(Comparator<? super T> comparator)  根据提供的比较器返回此流的最大元素。

    Optional<T> min(Comparator<? super T> comparator)  根据提供的比较器返回此流的最小元素。

    Optional<T> findAny()  返回一个描述流的某个元素的可选项,如果流为空,则返回一个空的可选项。

    Optional<T> findFirst()  返回描述此流的第一个元素的可选项,如果流为空,则返回一个空的可选项。 如果流没有遇到命令,则可以返回任何元素;

    noneMatch和allMatch它们分别会在所有元素和没有任何元素匹配断言的情况下返回true

    boolean allMatch(Predicate<? super T> predicate)

    boolean noneMatch(Predicate<? super T> predicate)

    boolean anyMatch(Predicate<? super T> predicate)

     1 /**
     2  * Created by Lenovo on 2017/12/20.
     3  * java.util.Optional<T>
     4  * public T orElse(T other) 返回值如果存在,否则返回其他。
     5  * java.lang.String
     6  * public int compareToIgnoreCase(String str) 按字母顺序比较两个字符串,忽略大小写的差异。
     7  *
     8  */
     9 public class Demo08 {
    10 
    11     private static final String filePath = "G:\Idea\src\com\itheima05\Test_JavaSE\Test_20171214\word.txt";
    12 
    13     public static void main(String[] args) throws Exception {
    14 
    15         String contents = new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    16         List<String> words = Arrays.asList(contents.split("\PL+"));
    17 
    18         //获取流中的最大值
    19         Optional<String> largest = words.stream().max(String::compareToIgnoreCase);
    20         System.out.println("largest:"+largest.orElse(""));
    21 
    22         //显示已字母为"Q"开头的单词
    23         Optional<String> firstWords = words.stream().filter(s -> s.startsWith("Q")).findFirst();
    24         System.out.println("firstWords:"+firstWords.orElse(""));
    25 
    26         //显示有字母为"Q"的单词
    27         Optional<String> anyWords = words.stream().filter(s -> s.startsWith("Q")).findAny();
    28         System.out.println("anyWords:"+anyWords.orElse(""));
    29 
    30         //判断是否匹配
    31         boolean anyMatch = words.parallelStream().anyMatch(s -> s.startsWith("Q"));
    32         System.out.println("anyMatch:"+anyMatch);
    33 
    34         boolean noneMatch = words.parallelStream().noneMatch(s -> s.startsWith("Q"));
    35         System.out.println("noneMatch:"+noneMatch);
    36 
    37         boolean allMatch = words.parallelStream().allMatch(s -> s.startsWith("Q"));
    38         System.out.println("allMatch:"+allMatch);
    39     }
    40 }
  • 相关阅读:
    Java代码编译执行的过程
    《Redis核心原理与实战》学习笔记7——有序集合使用与内部实现原理
    《Redis核心原理与实战》学习笔记6——集合使用与内部实现原理
    Eureka服务治理-注册中心和注册服务
    SpringCloud微服务概述
    MySQL索引问答10道
    MySQL基础问答15道
    《Redis核心原理与实战》学习笔记5——列表使用与内部实现原理
    《Redis核心原理与实战》学习笔记4——字典使用与内部实现原理
    《Redis核心原理与实战》学习笔记3——字符串使用与内部实现原理
  • 原文地址:https://www.cnblogs.com/qlwang/p/8060290.html
Copyright © 2020-2023  润新知