NLinker

Lazy Streams and side effects

Dec 16th, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.16 KB | None | 0 0
  1. package vertigo.app;
  2.  
  3. import java.util.stream.Stream;
  4.  
  5. public class LazyTest {
  6.  
  7.     public static void main(String[] args) {
  8.         example1();
  9.         example2();
  10.     }
  11.  
  12.     /** try to enable println and predict the output */
  13.     public static void example1() {
  14.         System.out.println("lazy streams and side effects");
  15.         Stream<Integer> s0 = Stream.of(1, 2, 4, 8, 45, 11);
  16.         Stream<Integer> s1 = s0.filter(x -> {
  17.             //System.out.println("x <<< " + x);
  18.             return x < 20;
  19.         });
  20.         Stream<Integer> s2 = s1.filter(x -> {
  21.             //System.out.println("x >>> " + x);
  22.             return x > 2;
  23.         });
  24.         s2.forEach(System.out::println);
  25.     }
  26.  
  27.     /** is the code safe? */
  28.     public static void example2() {
  29.         System.out.println("lazy streams and exceptions");
  30.         Stream<Integer> s0 = Stream.of(1, 2, 0, 8, 45, 11);
  31.         Stream<Double> s1;
  32.         try {
  33.             s1 = s0.map(x -> 1.0 / x);
  34.         } catch (Exception e) {
  35.             // found division by zero, return empty stream
  36.             s1 = Stream.empty();
  37.         }
  38.         s1.forEach(System.out::println);
  39.     }
  40. }
Add Comment
Please, Sign In to add comment