4. Java 8: Collection operations with Lambda Flashcards
How could you create a stream of Employee objects given the following class: class Employee { // Field and getters/setters omitted Employee(String name); }
Stream.of(new Employee(“Jan”), new Employee(“Henk”));
Given a Stream of Employee objects create a list of Integer objects. class Employee { // Field and getters/setters omitted Employee(String name); }
Stream employees = Stream.of(new Employee("Jan"), new Employee("Henk")); Stream names = employees.map(Employee::getName); Stream lenghts = names.map(String::lenght);
What are the primitive specialized Stream interfaces?
- IntStream
- DoubleStream
- LongStream
What are the Stream methods for mapping a Stream to a primitive specialized stream?
- mapToInt
- mapToLong
- mapToDouble
Primitive specialized streams come with some convenience methods, what are these methods?
min()
max()
sum()
average()
What is the difference between the findFirst and findAny method?
The findAny methods behavior is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations;
While findFirst while always return the first element (or an empty optional)
Using a Stream of String objects, use the anyMatch method to see if the name “Henk” is present.
Stream names = Stream.of(“Jan”, “Henk”, “Benny”);
boolean test = names.anyMatch(e -> “Henk”.equalsIgnoreCase(e)); // True
Using a Stream of String objects, use the allMatch method to determine if all names start with a “B”.
And use the noneMatch to determine that none of the names start with a “A”
Stream names = Stream.of(“Bob”, “Benny”);
names. allMatch(e -> e.startsWith(“B”)); // True
names. nonMatch(e -> e.startsWith(“A”)); // True
How would one create a empty Optional?
Optional.empty();
How would one create a Optional from a non-null object?
Optional.of(T);
How would one create a Optional from a object that might be NULL?
Optional.ofNullable(T);
What is the result of the following?
String s = null;
Optional optional = Optional.from(s);
System.out.println(optional.isPresent());
NullPointerException
Optional.of can only be used for non-null objects. If you want to wrap a (potential) null object use the Optional.ofNullable(T) factory method.
How can you retrieve the value of a Optional?
optional.get();
What is the difference between
Optional.orElse(T other)
or
Optional.orElseGet(Supplier extends T> other)
orElseGet is lazy
The supplier code is only executed when the Optional is really empty (it’s lazy). Whit orElse you really need to provide a object that is already created.
Give a Optional wrapping a String how would one write the code to get the value but if it doesn’t exist it will throw a IllegalArgumentException?
String s = null; Optional opt = Optional.ofNullable(s); String value = opt.orElseThrow(() -> new IllegalArgumentException());