Functional Programming With Java 简明教程

Intermediate Methods

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

Stream API was introduced in Java 8 to facilitate functional programming in Java. A Stream API is targeted towards processing of collections of objects in functional way. By definition, a Stream is a Java component which can do internal iteration of its elements.

流接口具有终结方法和非终结方法。非终结方法是会向流添加侦听器的那些操作。当流的终结方法被调用时,流元素的内部迭代开始,并且附加到流上的侦听器会针对每个元素被调用,结果由终结方法收集。

A Stream interface has terminal as well as non-terminal methods. Non-terminal methods are such operations which adds a listener to a stream. When a terminal method of stream is invoked, then internal iteration of stream elements get started and listener(s) attached to stream are getting called for each element and result is collected by the terminal method.

此类非终结方法称为中间方法。只有调用了终结方法,才能调用中间方法。以下是流接口的一些重要中间方法。

Such non-terminal methods are called Intermediate methods. The Intermediate method can only be invoked by called a terminal method. Following are some of the important Intermediate methods of Stream interface.

  1. filter − Filters out non-required elements from a stream based on given criteria. This method accepts a predicate and apply it on each element. If predicate function return true, element is included in returned stream.

  2. map − Maps each element of a stream to another item based on given criteria. This method accepts a function and apply it on each element. For example, to convert each String element in a stream to upper-case String element.

  3. flatMap − This method can be used to maps each element of a stream to multiple items based on given criteria. This method is used when a complex object needs to be broken into simple objects. For example, to convert list of sentences to list of words.

  4. distinct − Returns a stream of unique elements if duplicates are present.

  5. limit − Returns a stream of limited elements where limit is specified by passing a number to limit method.

Example - Intermediate Methods

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);
   }
}

Output

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