> 文章列表 > 02 中间操作

02 中间操作

02 中间操作

中间操作用于从一个流中获取对象,并将对象作为另一个流从后端输出,以连接到其他操作。

1 跟踪与调试:Stream.peek()

peek() 操作的目的是帮助调试。它允许你无修改地查看流中的元素

package com.hcong.streams;import java.io.IOException;/* @Classname Peeking* @Date 2023/4/14 14:51* @Created by HCong*/
public class Peeking {public static void main(String[] args) throws IOException {FileToWords.stream("E:\\\\Projects\\\\IdeaProjects\\\\OnJava\\\\src\\\\com\\\\hcong\\\\streams\\\\Cheese.dat").skip(10).limit(5).map(w -> w + " ").peek(System.out::print).map(String::toUpperCase).peek(System.out::print).map(String::toLowerCase).forEach(System.out::print);}
}
that THAT that conclusion CONCLUSION conclusion Well WELL well it IT it s S s 

2 流元素排序:Stream.sorted()

package com.hcong.streams;import java.io.IOException;/* @Classname SortedComparator* @Date 2023/4/14 14:56* @Created by HCong*/
public class SortedComparator {public static void main(String[] args) throws IOException {FileToWords.stream("E:\\\\Projects\\\\IdeaProjects\\\\OnJava\\\\src\\\\com\\\\hcong\\\\streams\\\\Cheese.dat").map(w -> w + " ").sorted().forEach(System.out::print);}
}

3 移除元素:Stream.distinct() 和 Stream.filter(Predicate)

  • distinct():在 Randoms.java 类中的 distinct() 可用于消除流中的重复元素。相比创建一个 Set 集合来消除重复,该方法的工作量要少得多。
  • filter(Predicate):过滤操作,保留如下元素:若元素传递给过滤函数产生的结果为 true
package com.hcong.streams;import java.util.stream.LongStream;import static java.util.stream.LongStream.iterate;
import static java.util.stream.LongStream.rangeClosed;/* @Classname Prime* @Date 2023/4/14 15:00* @Created by HCong*/
public class Prime {public static Boolean isPrime(long n) {return rangeClosed(2, (long) Math.sqrt(n)).noneMatch(i -> n % i == 0);}public LongStream numbers() {return iterate(2, i -> i + 1).filter(Prime::isPrime);}public static void main(String[] args) {new Prime().numbers().limit(10).forEach(n -> System.out.format("%d ", n));System.out.println();new Prime().numbers().skip(90).limit(10).forEach(n -> System.out.format("%d ", n));}
}

4 应用函数到元素:Stream.map()

使用 map() 映射多种函数到一个字符串流中。

  • map(Function):将函数操作应用在输入流的元素中,并将返回值传递到输出流 中。
  • mapToInt(ToIntFunction):操作同上,但结果是 IntStream
  • mapToLong(ToLongFunction):操作同上,但结果是 LongStream
  • mapToDouble(ToDoubleFunction):操作同上,但结果是 DoubleStream
package com.hcong.streams;import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Stream;/* @Classname FunctionMap* @Date 2023/4/14 15:28* @Created by HCong*/
public class FunctionMap {static String[] elements = {"12", "", "23", "45"};static Stream<String> testStream() {return Arrays.stream(elements);}static void test(String descr, Function<String, String> func) {System.out.println(" ---( " + descr + " )---");testStream().map(func).forEach(System.out::println);}public static void main(String[] args) {test("add brackets", s -> "[" + s + "]");test("Increment", s -> {try {return Integer.parseInt(s) + 1 + "";} catch (NumberFormatException e) {return s;}});test("Replace", s -> s.replace("2", "9"));test("Take last digit", s -> s.length() > 0 ?s.charAt(s.length() - 1) + "" : s);}
}
 ---( add brackets )---
[12]
[]
[23]
[45]---( Increment )---
1324
46---( Replace )---
1993
45---( Take last digit )---
23
5

5 组合流:Stream.flatMap()

  • flatMap() 做了两件事:将产生流的函数应用在每个元素上(与 map() 所做的相同),然后将每个流都扁平化为元素,因而最终产生的仅仅是元素。
  • flatMap(Function):当 Function 产生流时使用
  • flatMapToInt(Function):当 Function 产生 IntStream 时使用。
  • flatMapToLong(Function):当 Function 产生 LongStream 时使用。
  • flatMapToDouble(Function):当 Function 产生 DoubleStream 时使用。
package com.hcong.streams;import java.util.stream.Stream;/* @Classname FlatMap* @Date 2023/4/14 15:53* @Created by HCong*/
public class FlatMap {public static void main(String[] args) {Stream.of(1, 2, 3).flatMap(i -> Stream.of("Gonzo", "Fozzie", "Beaker")).forEach(System.out::println);}
}