Streams

streams

The Optional Type

Working with Optional

Your Turn

Which of these is the best way for searching for the first string containing an "e"?

  1. String result = words
      .filter(w -> w.contains("e"))
      .findFirst()
      .orElse("None");
    
  2. String result = words
      .filter(w -> w.contains("e"))
      .findFirst()
      .orElse("");
    
  3. String result = words
      .filter(w -> w.contains("e"))
      .findFirst()
      .orElse(null);
    
  4. Optional<String> result = words
      .filter(w -> w.contains("e"))
      .findFirst();
    

Returning Optional

Your Turn

Change this method so that it works for empty collections. Return an Optional result.

Other Terminal Operations

Primitive-Type Streams

Your Turn

Consider this code that operates on a Stream<Integer>:

long result = Stream.iterate(0, n -> n + 1)
   .limit(1000)
   .filter(n -> n % 2 == 0)
   .map(n -> n * 2)
   .count();

How many boxing and unboxing operations are necessary?

  1. 3000
  2. 3500
  3. 4000
  4. Something else

Creating Primitive-Type Streams

Mapping Primitive-Type Streams

Your Turn

Complete this method to process a stream of strings and yield the distinct lengths (in increasing order). Pay attention to efficiency:

Processing Primitive-Type Streams

Exercises

  1. Change this method so that it works with an Optional<Pair<Integer, Integer>>. For an empty Optional, return []. Do not use get.
  2. Implement this method so that it returns a sorted string of distinct vowels. As before, use Normalizer.normalize(str, Normalizer.Form.NFD) to take off accents, but now do this first, then convert to a stream of code points. When you filter the vowels, use a method expression. To turn the result back into a string, use the constructor new String(cps, 0, cps.length), where cps is an int[] array of code points.
  3. Complete this method that accepts an integer n and then yields all squares of the integers from 1 to n that are palindromes (that is, their decimal representation equals its reverse). Use IntStream.range, map or maybe mapToInt, filter, and toArray.
  4. (Hard) Complete this method that removes all adjacent duplicates of a stream, by using a predicate that compares each element against the previous one (stashed away in an array of length 1), updates the array, and returns the result of the comparison. You have to be careful with the first element.