OCP Flashcards – 5. Java Stream API

OCP Exam Objective 5 – Java Stream API

Flashcard OCP.5.Java.Stream.API.001

What is a stream pipeline?

Click here to view answer
A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

 

Flashcard OCP.5.Java.Stream.API.002

What do the stream intermediate operations return?

Click here to view answer
A Stream (in certain cases an int/long/double-valued specialization such as IntStream, LongStream and DoubleStream).

 

Flashcard OCP.5.Java.Stream.API.003

Which methods in the Stream interface return Optional?

Click here to view answer
findFirst(), findAny(), min(), max(), reduce(BinaryOperator)

 

Flashcard OCP.5.Java.Stream.API.004

Which methods in the Stream interface are intermediate operations?

Click here to view answer
Intermediate operations (15 in total):

filter(Predicate)
map(Function)
    mapToInt(ToIntFunction)
    mapToLong(ToLongFunction)
    mapToDouble(ToDoubleFunction)
flatMap(Function)
    flatMapToInt(Function)
    flatMapToLong(Function)
    flatMapToDouble(Function)
distinct()                     // returns a stream of distinct elements; stateful
sorted()                       // uses nator; stateful
sorted(Comparator)             // stateful
peek(Consumer)
limit(long)                    // short-circuiting stateful
skip(long)                     // stateful

Mnemonics:

       

A map? -> four cardinal points -> four map-related methods -> eight in total;

Difference between map() and flatMap()? Think of map() as a pastry mold or a cutter that gives a stream element a fancy shape, while flatMap() is more like a rolling pin that allows you to flatten a piece of dough to any size. In other words, map() is 1-to-1, while flatMap() is 1-to-any, including zero.

 

Flashcard OCP.5.Java.Stream.API.005

Which methods in the Stream interface are terminal operations?

Click here to view answer
Terminal operations (17 in total):

forEach(Consumer)
forEachOrdered(Consumer)        // supports encounter order if it exists (e.g., Lists and arrays vs. HashSet)
toArray()
toArray(IntFunction)
reduce(BinaryOperator)          // returns an Optional
reduce(T identity, BinaryOperator)
reduce(U identity, BiFunction, BinaryOperator)
collect(Collector)
collect(Supplier, BiConsumer, BiConsumer)
min(Comparator)                 // returns Optional
max(Comparator)                 // returns Optional
count()                         // returns long
anyMatch(Predicate)             // short-circuiting
allMatch(Predicate)             // short-circuiting
noneMatch(Predicate)            // short-circuiting
findFirst()                     // short-circuiting, returns Optional
findAny()                       // short-circuiting, returns Optional

 

Flashcard OCP.5.Java.Stream.API.006

What does peek() return?

Click here to view answer
This method is void.

 

Flashcard OCP.5.Java.Stream.API.007

What does the Optional<T> class represent?

Click here to view answer
A value that may be null, because it is not required.

 

Flashcard OCP.5.Java.Stream.API.008

Which Optional method returns an empty Optional if no value has been specified?

Click here to view answer
It’s ofNullable(T value), which returns an Optional<T> describing the specified value, if non-null, otherwise returns an empty Optional.

 

Flashcard OCP.5.Java.Stream.API.009

Which Optional method returns an Optional if provided a value?

Click here to view answer
It’s of(T value), which returns an Optional with the specified present non-null value.

 

Flashcard OCP.5.Java.Stream.API.010

Which search method arbitrarily returns an element from a stream?

Click here to view answer
findAny()

 

Flashcard OCP.5.Java.Stream.API.011

How many methods in the Stream interface return a stream of ints?

Click here to view answer
Two: it’s mapToInt() and flatMapToInt()

 

Flashcard OCP.5.Java.Stream.API.012

What does Stream‘s map() method do?

Click here to view answer
It applies the specified function to each element.

 

Flashcard OCP.5.Java.Stream.API.013

Which does flatMap() do?

Click here to view answer
It replaces each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

 

Flashcard OCP.5.Java.Stream.API.014

Which Optional methods return the value that is present in an Optional?

Click here to view answer
get()                          // throws NoSuchElementException on empty Optional
orElse(T other)                // returns other on empty Optional
orElseGet(Supplier other)      // returns other on empty Optional
orElseThrow(Supplier ex)       // throws Supplier-provided exception on empty Optional

 

Flashcard OCP.5.Java.Stream.API.015

Which Optional methods check whether an Optional contains something?

Click here to view answer
isPresent()
ifPresent(Consumer)            // consumes the value if it exists, otherwise does nothing

 

Flashcard OCP.5.Java.Stream.API.016

Which method simply appends one stream to another?

Click here to view answer
concat(Stream<? extends T> a, Stream<? extends T> b); returns a followed by b.

 

Flashcard OCP.5.Java.Stream.API.017

Which value will noneMatch() return if no element matches the specified Predicate?

Click here to view answer
true

 

Flashcard OCP.5.Java.Stream.API.018

Argument of which datatype does the peek() method accept?

Click here to view answer
Consumer

 

Flashcard OCP.5.Java.Stream.API.019

Which search method returns the element that is located at the stream’s head?

Click here to view answer
findFirst()

 

Flashcard OCP.5.Java.Stream.API.020

What does allMatch() return?

Click here to view answer
boolean

 

Flashcard OCP.5.Java.Stream.API.020

Which method will be executed first if they both present in a stream pipeline: findAny() or filter()?

Click here to view answer
filter()

 

Flashcard OCP.5.Java.Stream.API.021

Which Stream method returns a stream composed of the same elements all the while allowing to take advantage of side effects?

Click here to view answer
peek()

 

Flashcard OCP.5.Java.Stream.API.022

Which Stream re-arranges elements into their natural order?

Click here to view answer
sorted()

 

Flashcard OCP.5.Java.Stream.API.022

Which wrapper class in java.util.* helps deal with NullPointerException?

Click here to view answer
Optional<T>

 

Flashcard OCP.5.Java.Stream.API.023

Which stream method places elements into a mutable result container?

Click here to view answer
collect()

 

Flashcard OCP.5.Java.Stream.API.024

Which datatype is to passed to the anyMatch() method as its argument?

Click here to view answer
Predicate

 

Flashcard OCP.5.Java.Stream.API.025

Argument of which datatype should be passed to the sorted() method to re-arrange stream elements in a custom order?

Click here to view answer
Comparator<T>

 

Flashcard OCP.5.Java.Stream.API.026

What is the difference between a Stream interface object and a Stream pipeline object?

Click here to view answer
A Stream interface object is a sequence of elements, which supports sequential and parallel aggregate operations, while a Stream pipeline is a series of aggregate operations such as filtering, mapping or counting to be performed on those elements.

 

Flashcard OCP.5.Java.Stream.API.027

What parameter does the forEach() method require when invoked on a Map object?

Click here to view answer
A BiConsumer.

 

Flashcard OCP.5.Java.Stream.API.028

What does the following code do?

class Max{
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3);

        int maxValue = list.stream().max();
        
        System.out.println(maxValue);
    }
}
Click here to view answer
Flags a compilation error because Stream‘s max() needs a Comparator as its argument. The same goes for min().

 

Flashcard OCP.5.Java.Stream.API.029

How would you correct the previous code by providing an anonymous class that implements Comparator?

Click here to view answer
class Max{
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3);

        Optional<Integer> maxValue = list.stream().max(
                new Comparator<Integer>(){
                    @Override
                    public int compare(Integer o1, Integer o2){
                        return o1 - o2;
                    }
        });
        
        System.out.println(maxValue.get());      // ATTN to empty Optional scenario
    }
}

 

Flashcard OCP.5.Java.Stream.API.030

How would you replace the anonymous class from the previous question with a lambda?

Click here to view answer
        Optional<Integer> maxValue = list.stream().max( (o1, o2) -> o1 - o2 );

 

Flashcard OCP.5.Java.Stream.API.031

How would you take advantage of the int-valued primitive specialization of Optional in the previous example?

Click here to view answer
        OptionalInt maxValue = list.stream().mapToInt( x -> x ).max();

 

Flashcard OCP.5.Java.Stream.API.032

How would you replace the lambda from the previous example with a method reference?

Click here to view answer
        Optional<Integer> maxValue = list.stream().mapToInt( Integer::valueOf ).max();

 

Flashcard OCP.5.Java.Stream.API.033

What is an easy way to specify a natural-order-based Comparator for the Max class that we’ve been using in our previous examples?

Click here to view answer
        OptionalInt maxValue = list.stream().max(Comparator.naturalOrder());

 

Flashcard OCP.5.Java.Stream.API.034

True or false: The following LOC is valid although it is missing a terminal operation?

Stream.generate(Math::random).limit(10);

Click here to view answer
True

 

Flashcard OCP.5.Java.Stream.API.035

How many LOCs in the following code snippet are valid? Possible answers are none to all.

Stream<Integer>.of(1,2).count();      // n1
Stream.<Integer>of(1,2).count();      // n2
Stream.<>of(1,2).count();             // n3
Stream.of(1,2).count();               // n4

Click here to view answer
Two: n2 and n4

 

Flashcard OCP.5.Java.Stream.API.036

The Iterable<E> interface defines the Iterator<T> interator() and default void forEach(Consumer<? super T>) methods. What’s the difference? (For a moment we forget about the third and last method, spliterator())

Click here to view answer
iterator() was introduced (in 1.5) to make this object a target of the for-each stat, while forEach() performs the specified action on each element of the Collection.

Leave Comment

Your email address will not be published.