Optional Typenull to denote absence of resultNullPointerException when programmer forgets to check
String result = oldFashionedMethod(searchParameters); // Returns null if no match int length = result.length(); // Throws a NullPointerException when result is null
Optional type when a result may not be present.words.filter(w -> w.length() > 10).findFirst()
Optional<String> either contains a string or an indication that no value is present.
Optional<String> optResult = words .filter(w -> w.length() > 10) .findFirst();
Optionalnull reference.)orElse extracts the value or an alternative if there is none:
int length = optResult.orElse("").length();ifPresent passes on the value to a function; does nothing if there is none
optResult.ifPresent(v -> results.add(v));
isPresent to test if there is a value and get to get it.
if (optResult.isPresent())
{
System.out.println(optResult.get());
}
else
{
System.out.println("No element");
}Which of these is the best way for searching for the first string containing an "e"?
String result = words
.filter(w -> w.contains("e"))
.findFirst()
.orElse("None");
String result = words
.filter(w -> w.contains("e"))
.findFirst()
.orElse("");
String result = words
.filter(w -> w.contains("e"))
.findFirst()
.orElse(null);
Optional<String> result = words
.filter(w -> w.contains("e"))
.findFirst();
OptionalOptional<T>Optional.of(result)Optional.empty()public static Optional<Double> squareRoot(double x)
{
if (x >= 0) { return Optional.of(Math.sqrt(x)); }
else { return Optional.empty(); }
}Change this method so that it works for empty collections. Return an Optional result.
findAny is like findFirst, but is faster on parallel streams.
result = words
.parallel()
.filter(w -> w.length() > 10)
.filter(w -> w.endsWith("y"))
.findAny()
.orElse("");max/min require a comparator and return an Optional (since the input may be empty):
Optional<String> result = words.max((v, w) -> v.length() - w.length());
allMatch/anyMatch/noneMatch check a predicate:
boolean result = words.allMatch(w -> w.contains("e"));
// result is true if all words contain the letter eStream<Integer>numbers.map(x -> x * x) requires unboxing and boxing for each elementIntStream, DoubleStream, DoubleStream work with int, long, double values without boxingbyte, short, long, char, floatConsider 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?
IntStream stream = IntStream.of(3, 1, 4, 1, 5, 9); int[] values = . . .; stream = IntStream.of(values);
range yields a contiguous range of integers
IntStream stream = IntStream.range(a, b); // Stream contains a, a + 1, a + 2, ..., b -1
Random generator = new Random(); IntStream dieTosses = generator.ints(1, 7);
IntStream codePoints = str.codePoints();
charAt which only yields 16-bit code units of the variable-length UTF-16 encodingIntStream.map with an int -> int function yields another IntStream
IntStream stream = IntStream.range(0, 20) .map(n -> Math.min(n, 10)); // A stream with twenty elements 0, 1, 2, ..., 9, 10, 10, ..., 10
mapToObj:
String river = "Mississippi"; int n = river.length(); Stream<String> prefixes = IntStream.range(0, n) .mapToObj(i -> river.substring(0, i)); // "", "M", "Mi", "Mis", "Miss", "Missi", ...
mapToDouble, mapToLong if the function yields double, long valuesIntStream.range(a, b).mapXXX as an equivalent of a for loop that yields a value in each iteration.mapToInt/mapToLong/mapToDouble with streams of objects when the map function yields primitive type valuesboxed to turn into a stream of objectsComplete this method to process a stream of strings and yield the distinct lengths (in increasing order). Pay attention to efficiency:
IntStream for the lengthsIntStream.toArray returns an int[] and doesn't require a constructor sum, average, max, min (without comparators)OptionalInt/OptionalLong/OptionalDoubledouble average = words .mapToInt(w -> w.length()) .average() .orElse(0);
Optional<Pair<Integer, Integer>>. For an empty Optional, return []. Do not use get.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.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.