Sunday, July 2, 2017

Venkat Subramanian, Lazy evaluation in Streams




import java.util.Arrays;
import java.util.List;

public class Lazy {
 public static void main(String[] args) {
  List values = Arrays.asList(1, 2, 3, 5, 4, 6, 7, 8, 9);
  System.out.println(values.stream().filter(Lazy::isGT3).filter(Lazy::isEven).map(Lazy::doubleIt).findFirst().orElse(0));

 }

 public static boolean isGT3(int number) {
  System.out.println("isGT3 " + number);
  return number > 3;
 }
 

 public static boolean isEven(int number) {
  System.out.println("isEven " + number);
  return number % 2 == 0;
 }
 
 public static int doubleIt(int number) {
  System.out.println("doubleIt " + number);
  return number * 2;
 }


}




import java.util.stream.Stream;

public class SumEvenNumbers {
 public static int compute(int start, int count) {
  return Stream.iterate(start, e -> e + 1).filter(e -> e % 2 == 0).mapToInt(e -> e * 2).limit(count).sum();
 }
 
 public static void main(String[] args) {
  System.out.println(compute(51, 101));
 }

}




No comments: