3. Java 8: Filtering Collections with Lambda's Flashcards
How could you loop over the following list and print their values using the forEach method?
List names = new ArrayList<>();
names.add(“jordi”);
names.forEach(name -> System.out.println(name));
How could you loop over the following map and print the key and values using the forEach method?
Map settings = new HahsMap<>();
settings.put(“setting”, “option”);
settings.forEach((key, value) -> System.out.println(key + “:” + value));
What are the four intermediate stream operations that you need to know for the exam?
Stream filter(Predicate super T> predicate); Stream map(Function super T,? extends R> mapper); Stream distinct(); Stream peek(Consumer super T> action);
How can a stream be used to filter out all the items from a String list that do not start with a “a”. Given the lists name is names.
names.stream()
.filter(s-> s.startsWith(“a”)) // or s::startsWith;
.collect(Collectors.toList());
When the predicate returns true the item passes the filter and will move past it.
How can a stream be used to transform all Strings in a list to Uppercase? Given the list name is names.
names.stream()
.map(s -> s.toUpperCase())
.collect(Collectors.toList());
How can a stream be used to filter a list so that only the unique items remain? Given the list with String object is named names.
names.stream()
.distinct()
.collect(Collectors.toList());
How can a stream be used to print every item that passes by. Given the list with String object is named names.
names.stream()
.peek(s -> System.out.println(s))
.collect(Collectors.toList());
What are the six terminal stream operations that you need to know for the exam?
R collect(Collector super T, A, R> collector); Optional min(Comparator super T> comparator); Optional max(Comparator super T> comparator); Optional findAny(); Optional findFirst(); long count();
To collect the results of a stream operation several classes can be used. In what class you can find the built-in collectors?
Collectors
How is a Stream pipeline built?
- the first part is a source (an array, Collection, generator function, etc.)
- zero or more intermediate operations wich transform a Stream into another Stream.
- and finally one terminal operation which produces a result or side-effect. Such as count() or forEach(Consumer c);
Given the following code what is the result:
names.stream
.peek(s -> System.out.print(s));
Nothing. As long as there is no terminal operation intermediate operations are not executed therefore streams are considered lazy.
Given the following code what is the result:
List names =Arrays.asList(“Volha”, “Ivan”, “John”);
String name = names.stream();
.filter(s -> { System.out.println(“filtering: “ + s); return s.lenght == 4; })
.map(s -> { System.out.println(“uppercasing: “ + s); return s.toUpperCase(); })
.findFirst().get();
System.out.println(name);
filtering: Volha
filtering: Ivan
uppercasing: Ivan
IVAN