中间方法



Stream API 在 Java 8 中引入,旨在促进 Java 中的函数式编程。Stream API 针对以函数式方式处理对象集合。根据定义,Stream 是一个 Java 组件,可以对其元素进行内部迭代。

Stream 接口具有终止方法和非终止方法。非终止方法是指向流添加监听器的操作。当调用流的终止方法时,流元素的内部迭代开始,并且附加到流的监听器将为每个元素调用,结果由终止方法收集。

此类非终止方法称为中间方法。中间方法只能通过调用终止方法来调用。以下是 Stream 接口的一些重要的中间方法。

  • filter − 根据给定条件从流中过滤掉不需要的元素。此方法接受一个谓词并将其应用于每个元素。如果谓词函数返回 true,则元素包含在返回的流中。

  • map − 根据给定条件将流的每个元素映射到另一个项目。此方法接受一个函数并将其应用于每个元素。例如,将流中每个字符串元素转换为大写字符串元素。

  • flatMap − 此方法可用于根据给定条件将流的每个元素映射到多个项目。当需要将复杂对象分解为简单对象时,使用此方法。例如,将句子列表转换为单词列表。

  • distinct − 如果存在重复项,则返回唯一元素的流。

  • limit − 返回一个元素有限的流,其中限制通过将数字传递给 limit 方法来指定。

示例 - 中间方法

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

public class FunctionTester {    
   public static void main(String[] args) {
      List<String> stringList = 
         Arrays.asList("One", "Two", "Three", "Four", "Five", "One");       

      System.out.println("Example - Filter\n");
      //Filter strings whose length are greater than 3.
      Stream<String> longStrings = stringList
         .stream()
         .filter( s -> {return s.length() > 3; });

      //print strings
      longStrings.forEach(System.out::println);

      System.out.println("\nExample - Map\n");
      //map strings to UPPER case and print
      stringList
         .stream()
         .map( s -> s.toUpperCase())
         .forEach(System.out::println);

      List<String> sentenceList 
         = Arrays.asList("I am Mahesh.", "I love Java 8 Streams.");     

      System.out.println("\nExample - flatMap\n");
      //map strings to UPPER case and print
      sentenceList
         .stream()
         .flatMap( s -> { return  (Stream<String>) 
            Arrays.asList(s.split(" ")).stream(); })
         .forEach(System.out::println);     

      System.out.println("\nExample - distinct\n");
      //map strings to UPPER case and print
      stringList
         .stream()
         .distinct()
         .forEach(System.out::println);     

      System.out.println("\nExample - limit\n");
      //map strings to UPPER case and print
      stringList
         .stream()
         .limit(2)
         .forEach(System.out::println);        
   }   
}

输出

Example - Filter

Three
Four
Five

Example - Map

ONE
TWO
THREE
FOUR
FIVE
ONE

Example - flatMap

I
am
Mahesh.
I
love
Java
8
Streams.

Example - distinct

One
Two
Three
Four
Five

Example - limit

One
Two
广告

© . All rights reserved.