Java Stream How to - Chain functions








The following code shows how to chain functions.

Example

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
//from   w  w  w. jav a 2  s.  c  o m
public class Main {
   public static void main(String[] args) {
      Function<Double, Double> square = number -> number * number;
      Function<Double, Double> half = number -> number * 2;

      List<Double> numbers = Arrays.asList(10D, 4D, 12D);

      // pay attention to the order
      System.out.println(mapIt(numbers, square.compose(half)));
      System.out.println(mapIt(numbers, half.compose(square)));

      // you can chain them
      System.out.println(mapIt(numbers, half.andThen(square)));

   }

   private static List<Double> mapIt(List<Double> numbers, Function<Double, Double> fx) {
      List<Double> result = new ArrayList<>();

      for (Double number : numbers) {
         result.add(fx.apply(number));
      }

      return result;
   }
}

The code above generates the following result.