Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package vertigo.app;
- import java.util.stream.Stream;
- public class LazyTest {
- public static void main(String[] args) {
- example1();
- example2();
- }
- /** try to enable println and predict the output */
- public static void example1() {
- System.out.println("lazy streams and side effects");
- Stream<Integer> s0 = Stream.of(1, 2, 4, 8, 45, 11);
- Stream<Integer> s1 = s0.filter(x -> {
- //System.out.println("x <<< " + x);
- return x < 20;
- });
- Stream<Integer> s2 = s1.filter(x -> {
- //System.out.println("x >>> " + x);
- return x > 2;
- });
- s2.forEach(System.out::println);
- }
- /** is the code safe? */
- public static void example2() {
- System.out.println("lazy streams and exceptions");
- Stream<Integer> s0 = Stream.of(1, 2, 0, 8, 45, 11);
- Stream<Double> s1;
- try {
- s1 = s0.map(x -> 1.0 / x);
- } catch (Exception e) {
- // found division by zero, return empty stream
- s1 = Stream.empty();
- }
- s1.forEach(System.out::println);
- }
- }
Add Comment
Please, Sign In to add comment