Ch15 Functional Programming Flashcards

1
Q

Which functional interface from java.util.function takes 1 parameter (T) and returns a generic object (T)?

A

UnaryOperator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What method does the Supplier functional interface have?

A

get()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What method does the Consumer and BiConsumer functional interfaces have?

A

accept(T)
accept(T, U)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What method does the Predicate and BiPredicate functional interfaces have?

A

test(T)

test(T, U)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What method does the Function and BiFunction functional interfaces have?

A

apply(T)
apply(T, U)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When should the Function interface be used?

A

When you want to turn one parameter into a value of potentially different type and return it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which functional interface should be used when you want to combine two strings and return a new one?

A

BiFunction or BinaryOperator (better)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Is the following code valid?

UnaryOperator u1 = String::length;

A

No. The statement returns an Integer but UnaryOperator requires the return type be the same as the input type (String).

To make this code valid, Function needs to be used.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is wrong with the following statement?

Function< List> ex = x -> x.get(0);

A

A Function always needs to specify two generics, one input and one output type.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is wrong with the following statement?

Predicate ex = String::isEmpty;

A

Predicate expects a generic but since it wasn’t supplied, the parameter that was passed in is treated as an Object, instead of a String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What convenience methods does Predicate contain?

A
  • and()
  • negate()
  • or()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can the following code be rewritten using conveniance methods?

Predicate brownEggs = s -> s.contains(“egg”) && s.contains(“brown”);

A
  • Predicate egg = x -> x.contains(“egg”);
  • Predicate brown = x -> x.contains(“brown”);
  • Predicate brownEgg = egg.and(brown);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can the following code be rewritten using conveniance methods?

Predicate NonBrownEggs = s -> s.contains(“egg”) && !s.contains(“brown”);

A
  • Predicate egg = x -> x.contains(“egg”);
  • Predicate brown = x -> x.contains(“brown”);
  • Predicate NonBrownEggs = egg.and(brown.negate());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What convenience methods does Consumer contain?

A

andThen()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What convenience methods does Function contain?

A
  • andThen()
  • compose()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What conveniance method can be used to combine the following consumers?

Consumer c1 = x -> System.out.println(x);
Consumer c2 = x -> System.out.println(x);

A

andThen()

Consumer combined = c1.andThen(c2);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What conveniance method can be used to pass the output of f1 to the input of f2?

Function f1 = x -> x + 1;
Function f2 = x -> x * 2;

A

compose()

Function combined = f2.compose(f1);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the following code do?

Optional opt = Optional.empty();
opt.get();

A

Throws a NoSuchElementException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do we prevent the code from throwing an exception (without using a try-catch)?

Optional opt = Optional.empty();
opt.get()

A

replace opti.get() with:

if (opt.isPresent())
opt.get();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What does the Optional static method ofNullable() do?

A

Creates an empty optional if the provided value is null or creates an optional with the value if it is not null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What does the Optional instance method ifPresent(Consumer c) do if the Optional is empty?

A

Does nothing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What does the Optional instance method ifPresent(Consumer c) do if the Optional contains a value?

A

Calls Consumer with value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How can we use Optional to get the value, or else throw a specific exception if it is empty?

A

Using the method orElseThrow().

We can leave the parameters empty to throw a NoSuchElementException, or provide a Supplier to throw another exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Why does the following code not compile?

Optional<Double> opt = Optional.empty();
System.out.println(opt.orElseGet(() -> new IllegalStateException()));

A

No it doesn’t.

The opt variable is an Optional with generic Double which means the Supplier must return a Double. This Supplier returns an exception instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is a stream pipeline in Java?

A

A stream pipeline consists of the operations that run on a stream to produce a result.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What are the parts of the stream pipeline?

A
  • source: where the stream comes from
  • Intermediate operations: Transforms the stream into another one.
  • Terminal operation: actually produces a result. The stream is no longer valid after a terminal operation completes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

The Stream interface is located in what package?

A

java.util.stream

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What are ways to create finite Streams?

A

Stream.empty()
Stream.of(varargs)
someCollection.stream()
someCollection.parallelStream()
Stream.iterate(seed, predicate, unaryOperator)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Given the following list (or any other Collection), how do we create a stream out of this?

var list = List.of(“a”, “b”, “c”);

A

Stream fromList = list.stream();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Given the following list (or any other Collection), how do we create a parallel stream out of this?

var list = List.of(“a”, “b”, “c”);

A

Stream fromList = list.parallelStream();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are ways to create infinite Streams?

A
  • Stream.generate(supplier)
  • Stream.iterate(seed, unaryOperator)
  • Stream.iterate(seed, predicate, unaryOperator)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Make a statement for creating an infinite stream that returns random numbers.

A

Stream randoms = Stream.generate(Math::random);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

Make a statement for creating an infinite stream that returns every odd number.

A

Stream oddNums = Stream.iterate(1, n -> n + 2);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

Make a statement for creating an infinite stream that returns every odd number, less than 100.

A

Stream oddNums = Stream.iterate(1, n -> n < 100, n -> n + 2);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Does count() terminate infinite streams?

A

no

36
Q

What does the Stream method min() & max() do?

A

The min() and max() take a Comparator and find the smallest or largest value in a stream.

37
Q

Given the following stream, how can we print the shortest string, if present?

Stream s = Stream.of(“monkey”, “ape”, “bonobo”);

A

Optional min = s.min((s1, s2) -> s1.length()-s2.length());

min.ifPresent(System.out::println);

38
Q

What do the Stream method min() and max() return?

A

An Optional

39
Q

What do the Stream method anyMatch(), allMatch() & noneMatch() do?

A

Search a stream and return information about how the stream pertains to the predicate.

40
Q

What does the reduce() method do? (streams)

A

The reduce() method combines a stream into a single object. It is a reduction, which means it processes all elements.

41
Q

What are the method signatures for reduce()? (streams)

A
  • T reduce (T identity, BinaryOperator<T> accumulator)
  • Optional<T> reduce(BinaryOperator<T> accumulator)
  • <U> U reduce(U identity, BiFunction<U, ? super T,U> accumulator, BinaryOperator<U> combiner)
42
Q

What is the identity of a reduce() method? (streams)

A

Identity – an element that is the initial value of the reduction operation and the default result if the stream is empty

43
Q

What is the accumulator of a reduce() method? (streams)

A

Accumulator – a function that takes two parameters: a partial result of the reduction operation and the next element of the stream

44
Q

What is the combiner of a reduce() method? (streams)

A

Combiner – a function used to combine the partial result of the reduction operation when the reduction is parallelized or when there’s a mismatch between the types of the accumulator arguments and the types of the accumulator implementation

45
Q

What does the following code print?

Stream numbers = Stream.of(1,2,3,4,5,6);
int result = numbers.reduce(0, (n1, n2) -> n1 + n2);
System.out.println(result);

A

21

46
Q

What does the following code print?

Stream numbers = Stream.of(“1”);
Optional result = numbers.reduce((n1, n2) -> n1 + n2);
System.out.println(result.get());

A

1

If there is one value, it will be returned by reduce(). the accumulator won’t be applied.

47
Q

What does the following code print?

    Stream<String> stream = Stream.of("w", "o", "l", "f!");
    var result = stream.reduce(0, (i, s) -> i+s.length(), (a, b) -> a+b);
    System.out.println(result);
A

5

48
Q

What does the collect() method do? (streams)

A

The collect() method is a reduction method that uses a mutable object to transform data from a stream.

49
Q

What does the distinct() method do? (streams)

A

The distinct() method returns a Stream with duplicate values removed. Java does this by calling equals() on the elements.

50
Q

What does the limit() and skip() method do? (streams)

A

The limit() and skip() methods can make a Stream smaller, or they could make a finite stream out of an infinite stream.

Stream limit(long maxSize)
Stream skip(long n)

51
Q

What does the following code print?

Stream s = Stream.iterate(1, n -> n + 1);
s.skip(5).limit(2).forEach(System.out::println);

A

6

7

52
Q

What does the map() method do? (streams)

A

The map() method creates one-to-one mapping from the elements in the stream to the elements of the next step in the stream.

53
Q

What does the following code print?

Stream s = Stream.of(“monkey”, “gorilla”);
s.map(String::length).forEach(System.out::println);

A

6

7

54
Q

What does the flatMap() method do? (streams)

A

The flatMap() method takes each element in the stream and makes any elements it contains top-level elements in a single stream.

This is helpful when you want to remove empty elements from a stream or you want to combine a stream of lists.

55
Q

What does the following code print?

List zero = List.of();
var one = List.of(“Bonobo”);
var two = List.of(“Mama Gorilla”, “Baby Gorilla”);
Stream> animals = Stream.of(zero, one, two);
animals.flatMap(m -> m.stream()).forEach(System.out::println);

A

Bonobo
Mama Gorilla
Baby Gorilla

56
Q

What does the sorted() method do? (streams)

A

The sorted() method returns a stream with the elements sorted. Java uses natural ordering unless we specify a comparator.

57
Q

What is the result of the following code?

Stream s = Stream.of(“monkey”, “gorilla”);
s.sorted(Comparator::reverseOrder);

A

The method reverseOrder() is not compatible with the abstract method that is defined in Comparator (different parameters and return type).

Stream sorted method:
Stream<T> sorted​(Comparator<? super T> comparator)</T>

It takes in a comparator object as the input parameter, not a functional interface (lambda)

This however, works:

s.sorted(Comparator.reverseOrder());

58
Q

What does the peek() method do? (streams)

A

The peek() method allows us to perform a stream operation without actually changing the stream.

Stream peek(Consumer< ? super T> action)

59
Q

What does the following code do?

Stream.generate(() -> “Elsa”).filter(x -> x.length() == 4).sorted().limit(2).forEach(System.out::println);

A

It hangs until you kill the program or it throws an exception after running out of memory.

The sorted() method waits until everything to sort is present. That never happens because there is an infinite stream.

60
Q

What does the following code do?

Stream.generate(() -> “Elsa”).filter(x -> x.length() == 4).limit(2).sorted().forEach(System.out::println);

A

This prints “Elsa” twice.

The filter lets elements through, and limit() stops the ealier operations after two elements. Now sorted() can sort because we have a finite list.

61
Q

What are the types of Primitive Streams?

A
  • IntStream
  • LongStream
  • DoubleStream
62
Q

What is the difference between the primitive stream method range(a, b) and rangeClosed(a, b)?

A

range() returns a primitive stream from a (inclusive) to b (exclusive)

rangeClosed() returns a primitive stream from a (inclusive) to b (inclusive)

63
Q

What method can we use to map from a Stream to a IntStream?

A

mapToInt()

64
Q

What method can we use to map from a IntStream to a Stream?

A

mapToObj()

65
Q

What is the difference with OptionalDouble and Optional?

A

OptionalDouble is for a primitive, while Optional is for a Wrapper class.

66
Q

What is the return type of the method average() on any primitive stream?

A

OptionalDouble.

It is always double because the result could always become one.

67
Q

What is the type of var?

LongStream longs = LongStream.of(5, 10);
var sum = longs.sum();

A

long.

Calling sum will always return the primitive associated with the stream.

68
Q

What is the output?

var cats = new ArrayList();
cats.add(“Rody”);
var stream = cats.stream();
cats.add(“Pooh”);
System.out.println(stream.count());

A

2.

Streams are lazily evaluated, which means that the stream isn’t actually created on the line where stream is assigned. Instead, an object is created that knows where to look for the data when it is needed.

The stream actually runs when count() is called.

69
Q

Given the following stream, which collector should be used to create a single String where the words are seperated by commas? (lions, tigers, bears)

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
String result = ohMy.collect(…);

A

Collectors.joining(“, “);

Collectors.joining(delimiter, prefix, suffix) method

String joined = colors.stream().collect(Collectors.joining(“, “, “{“, “}”));

{RED, BLUE, BLACK, GREEN}

70
Q

Given the following stream, which collector should be used to get the average length of all elements?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Double result = ohMy.collect(…);

A

Collectors.averagingInt(String::length);

71
Q

Given the following stream, which collector should be used to Transform it into a TreeSet?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeSet result = ohMy.collect(…);

A

Collectors.toCollection(TreeSet::new);

72
Q

Given the following stream, which Collector should be used to transform the stream into a map, where the key is the element and the value is the length?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Map result = ohMy.collect(…);

A

Collectors.toMap(s -> s, String::length);

73
Q

What code must be added to fix the exception that will be thrown here?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Map result = ohMy.collect(Collectors.toMap(
String::length,
k -> k));

A

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeMap result = ohMy.collect(Collectors.toMap(
String::length,
k -> k,
(s1, s2) -> s1 + “,” + s2,
TreeMap::new));

(note the mergeFunction, which will be called to resolve conllision with values with the same key)

74
Q

What Collectors method can we use to create a Map of List that is grouped by its length (key)?

A

Collectors.groupingBy(String::length);
groupingBy determines the key of the map.

75
Q

Fill in the blanks to comply with the type of result, where Integer is the length of the string and Set is a set of values that has that length.

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Map< Integer, Set> result = ohMy.collect(…);

A

Collectors.groupingBy(String::length, Collectors.toSet()))

76
Q

Fill in the blanks to comply with the type of result, where Integer is the length of the string and Set is a set of values that has that length.

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeMap< Integer, Set> result = ohMy.collect(…);

A

Collectors.groupingBy(String::length, TreeMap::new, Collectors.toSet()))

77
Q

Fill in the blanks to comply with the type of result, where Integer is the length of the string and List is a set of values that has that length.

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeMap<Integer, List> result = ohMy.collect(…);

A

Collectors.groupingBy(String::length, TreeMap::new, Collectors.toList()))

78
Q

Is the function in groupingBy() allowed to return null?

A

No. It does not allow null keys.

79
Q

How can we partition the list with animals of length > 5 and animals with length <= 5?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Map> result = ohMy.collect(…);

A

Collectors.partitionBy( s -> s.length() < = 5));

80
Q

Fill in the blanks to group all animals by name length (key) and the amount that have that length (value).

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
Map<Integer, Long> result = ohMy.collect(…);

A

Collectors.groupingBy(String::length, Collectors.counting())

81
Q

What are the reduction methods?

bonus: which one is a mutable reduction?

A
  • collect() // mutable
  • count()
  • max()
  • min()
  • reduce()
82
Q

What are the terminal operations?

A
  • collect()
  • forEach()
  • min()
  • reduce()
  • count()
  • max()
  • findFirst()
  • findAny()
  • anyMatch()
  • allMatch()
  • noneMatch()
83
Q

What happens when anyMatch(), allMatch() or noneMatch() are used in an infinite stream?

A

They hang.

84
Q

What do findFirst() and findAny() return?

A

An Optional

85
Q

What does the Stream method findAny() & findFirst() do?

A

Return an element of the stream unless the stream is empty. They always return an Optional.

86
Q

How do we make the following code guarantee it returns a TreeMap?

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeMap result = ohMy.collect(Collectors.toMap(
String::length,
k -> k,
(s1, s2) -> s1 + “,” + s2));

A

var ohMy = Stream.of(“lions”, “tigers”, “bears”);
TreeMap result = ohMy.collect(Collectors.toMap(
String::length,
k -> k,
(s1, s2) -> s1 + “,” + s2,
TreeMap::new));