Functional Programming Flashcards

1
Q

What are the variable access rules for lambdas? what else shares these same rules?

A

lambdas can access static variables, instance variables, and effectively final local variables, effectively final method parametersinner classes share same rules

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

Supplier functional interface: What are the - params - return type - single abstract method

A

Supplier- 0 params- return type T- get

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

Consumer functional interface: What are the - params - return type - single abstract method

A

Consumer- 1 (T)- void- accept

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

BiConsumer functional interface: What are the - params - return type - single abstract method

A

BiConsumer- 2 (T, U)- void- accept

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

Function functional interface: What are the - params - return type - single abstract method

A

Function- 1 (T)- return type R- apply

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

BiFunction functional interface: What are the - params - return type - single abstract method

A

BiFunction- 2 (T, U)- return type R- apply

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

Predicate functional interface: What are the - params - return type - single abstract method

A

Predicate- 1 (T)- return type boolean- test

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

BiPredicate functional interface: What are the - params - return type - single abstract method

A

BiPredicate- 1 (T, U)- return type boolean- test

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

UnaryOperator functional interface: What are the - params - return type - single abstract method

A

UnaryOperator- 1 (T)- return type T- apply

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

BinaryOperator functional interface: What are the - params - return type - single abstract method

A

BinaryOperator- 2, (T, T)- return type T- apply

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

What is a supplier functional interface often used for?

A

supply no paramsreturn something- creating new objects Supplier> s1 = ArrayList::new;ArrayList a1 = s1.get();

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

what is a consumer functional interface often used for?

A
  • supply 1 or 2 params- return void
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

what is predicate functional interface often used for?

A
  • supply 1 or 2 params- return boolean
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are 2 default methods on predicates used to chain predicates?

A

Predicate.and(Predicate)- can combine together predicate conditionsPredicate.negate()- can negate a predicate condition

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

What is a Function/BiFunction functional interface often used for?

A
  • supply 1 or 2 params- return same or different type
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a UnaryOperator/BinaryOperator functional interface often used for? what other functional interface is it related to?

A
  • supply 1 or 2 params of same type- return same type- specialized version of Function/BiFunction
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does Optional.empty() return?

A

an Optional object with no value

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

What happens if you have an empty Optional and call optional.get()

A

NoSuchElementException is thrown

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

What Optional factory method would you use to wrap a value if it exists, or wrap empty if a value does not exist?

A

Optional.ofNullable(value);

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

How would you check if an Optional has a value?

A

optional.isPresent()

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

How would you get the value from an Optional?

A

optional.get()

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

How can you call Consumer c with value if an Optional value is present? What happens if value is not present?

A

anOptional.ifPresent(Consumer c)nothing

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

How can you define a default value if none exists in the Optional? What happens if value is present?

A

“anOptional.orElse(““value”“)value returned”

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

How can you call a Supplier s if an Optional value is not present? What happens if value is present?

A

anOptional.orElseGet(Supplier s)value returned

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How can you thrown an exception using a Supplier if Optional value is not present? What happens if value is present?
anOptional.orElseThrow(Supplier s)value returned
26
What is stream in Java?
a sequence of data
27
What is a stream pipeline?
operations that run on a stream to produce a result
28
what are the 3 parts of a stream pipeline?
source - where stream comes fromintermediary operations - transforms stream into anotherterminal operation - actually produces a result
29
how many times can stream result from a terminal operation be used?
once
30
how many times can stream result from a intermediary operation be used?
as many times as you want
31
when are intermediary vs terminal operations called?
intermediary - lazy evaluation - not called until terminal operation runterminal - run when method called
32
does an intermediary or a terminal operation return a stream type?
intermediary - yesterminal - no
33
can there be multiple intermediary or terminal operations in a pipeline?
multiple intermediarysingle terminal
34
are intermediary or terminal operations required in a pipeline?
intermediary - noterminal - yes
35
how do you create a stream of 0, 1, and multiple elements?
Stream.empty()Stream.of(1)Stream.of(1, 2, 3)- remember this takes var args, so you can list 1 or more elements
36
how do you create a stream from a list? how do you create a stream that can have intermediary operations run in parallel?
list.stream();list.parallelStream();
37
how would you create an infinite stream of random Double values and print them out?
Stream doubles = Streams.generate(Math::random);doubles.forEach(System.out::println);
38
how would you create a stream that has a seed or starting value and processes that value?
Stream oddNumbers = Stream.iterate(1, n -> n+2)
39
What is a reduction? what is an example of a reduction?
special type of terminal operation where all contents of stream are combined into a single primitive or Objectex: count() - method a long - the number of elements in stream
40
What happens if count() is called on an infinte stream?
the thread hangs - since it's counting to infinity
41
What do min() and max() do if called on finite vs. infinite stream? are these reductions?
finite - return min and max Optional valuesinfinite - thread hangsyes, reductions since they return a single value and process all values in stream
42
What do findAny() and findFirst() do?
findAny() - returns an Optional with any valuefindFirst() - returns an Optional with the first value in the stream
43
Why would you use findAny() over findFirst()?
findAny() works with parallel streams
44
are findAny() and findFirst() reductions? do they terminate?
they are NOT reductions since they may not process the entire stream sequence before returningthey do terminate, they work with infinite streams
45
what do allMatch() and noneMatch() do for infinite vs finite streams?
infinite - allMatch can terminate if a single element doesn't match. noneMatch can terminate if a single element matches.finite - return whether all match given the predicate param or none match given the predicate paramallMatch(Predicate p)noneMatch(Predicate p)
46
what does anyMatch() do for infinite vs finite streams?
infinite - could terminate if a match is foundfinite - always terminates whether match is found or not
47
once a Stream method is run on a given stream - allMatch(), count(), etc. - can we reuse that stream for a different result?
no, stream results can only be used once
48
what does the stream method forEach() do and what does it return?
it loops through the Stream elements- hangs for infinite streams- returns void
49
Can you call forEach directly on a Stream or a Collection?
both
50
can Streams use the traditional for loop since they can use forEach?
no, streams do not implement IterableforEach for streams is actually a terminal operator for streams, not a loop
51
"create a stream with 3 elements - ""w"", ""o"", ""l"" create a String that represents the stream elements concatenated 1) use a lambda 2) use method reference"
"Stream s = Stream.of(""w"", ""o"", ""l"");s.reduce("""", (s1, s2) -> s1 + s2);Stream s = Stream.of(""w"", ""o"", ""l"");s.reduce("""", String::concat);"
52
write a reduction to multiply all of the Integer objects in a stream
Stream integers = Stream.of(1, 2, 3, 4);Integer result = integers.reduce(1, (x,y) -> x*y);
53
when does reduce() return an optional?
if no identity is specified
54
what is returned for reduce() for the following 1) empty stream 2) single element 3) multiple elements
1) empty Optional2) single element3) reduction applied
55
what is special about collect()?
it is a mutable reduction
56
what is a mutable reduction?
more efficient because the same mutable object is used while accumulating
57
what are two method signatures for Stream.collect()?
R collect(Supplier supplier, BiConsumer accumulator, BiConsumer Combiner) R collect(Collector super T>, A, R> collector
58
"how would you use collect(3 params) to return a StringBuilder object from a Stream that contains the letters in the word ""happy""?"
"Stream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y"");StringBuilder result = s.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);"
59
"Stream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y""); StringBuilder result = s.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append); what is the 3rd parameter used for in collect()?"
used for processing parallel collections - if there were multiple data collections, it would be responsible for merging collections together
60
"how would you use collect(single param) to return a StringBuilder object (don't care about order) from a Stream that contains the letters in the word ""happy""? how would you use collect(single param) to return a StringBuilder object (DO care about order) from a Stream that contains the letters in the word ""happy""?"
"Stream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y"");StringBuilder result = s.collect(Collectors.toSet(s));Stream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y"");StringBuilder result = s.collect(Collectors.toCollection(TreeSet::new));"
61
what are the Collectors static methods used for?
commonly used scenarios for Streams.collect()
62
how do intermediary operations differ from terminal operations when dealing with infinite streams?
intermediary operations return an infinite stream and no hung threads - intermediary only deals with one element at a time
63
what does filter() do?
"filter(Predicate super T> predicate)takes a predicate and filters a streamStream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y"");s.filter(a -> a.length == 1).forEach(System.out::print);// prints happy"
64
what does distinct() do?
"Stream distinct()returns all distinct values in a streamStream s = Stream.of(""h"", ""a"", ""p"", ""p"", ""y"");s.distinct().forEach(System.out::print);// prints hapy"
65
what do skip() and limit() do?
both return streamsskip(int m) - returns stream after skipping first m elementslimit(int n) - returns max size by taking first n elements
66
what does map() do?
creates a one-to-one mapping from stream elements to the next step in the stream, signified by the Function parameterStream map(Function super T, ? extends R)- original stream is of type T- Function can take ? super T- returns a steam of type R
67
"how would you return the lengths of this stream using map? Stream s = Stream.of(""hello"", ""from"", ""the"", ""other"", ""side);"
"Stream s = Stream.of(""hello"", ""from"", ""the"", ""other"", ""side);s.map(String::length).forEach(System.out::println);// prints 54354"
68
what is flatMap() used for?
"it is used when you want to combine lists or make all elements in a stream top level elementsList s1 = Arrays.asList(""hello"", ""from"", ""the"", ""other"", ""side);List s2 = Arrays.asList(""called"", ""a"", ""mil"", ""times"");Stream lyrics = Stream.of(s1, s2);lyrics.flatMap(l -> l.stream()).forEach(System.out::println);// printshellofromtheothersidecalledamiltimes"
69
"does this compile? Stream s = Stream.of(""a"", ""b""); s.sorted(Comparator::reverseOrder);"
no, because reverseOrder takes 0 params and returns a parameterthe method signaturesorted(Comparator super T> comparator)in order to use a method reference, the method called must adhere to the comparator interface - meaning the method reference must take 2 params and return an integer as the compare(Object a, Object b) dictates in the functional interface
70
what's the difference between queue peek() and stream peek()?
queue - only takes a look at the top elementstream - takes a look at every element as it passes by the pipeline
71
can/should peek() modify the underlying stream data?
it shouldn't, but Java doesn't prevent you from doing it
72
how would you use streams to print alphabetically the first 2 names in a stream that are 4 char long?
"List names = Arrays.asList(""Abby"", ""Barry"", ""Charlie"", ""Dean"", ""Evan"");names.stream().filter(x -> x.length() == 4).sorted().limit(2).forEach(System.out::println);"
73
What are the 3 types of primitive streams?
IntStream - byte, short, int, charLongStream - longDoubleStream - double, float
74
how do you use generate() and iterate() for a stream?
generate(lambda function or method reference that returns the type specified by streamDoubleStream random = DoubleStream.generate(Math::random) -- this compiles because Math.random() generates random doublesiterate(int start, lambda function)IntStream s = IntStream.iterate(2, x -> x*4);- this would generate an IntStream of 2, 4, 8, etc.
75
how do you print a int 1-5 using range() and rangeClosed()
IntStream.range(1, 6)IntStream.rangeClosed(1, 5)
76
How do you map from one stream type to another stream type?
mapTo[stream type here]mapping from any stream type to DoubleStream:objStream.mapToDouble(lambda for mapping);
77
how do you map from one stream type to the same stream type?
objStream.map(lambda for mapping)
78
What does IntStream.summaryStatistics return?
IntStream ints = Intstream.empty()IntSummaryStatistics s = ints.summaryStatistics();useful when you need several calculations from a stream- min- max- average- size- # elements
79
how do you use a BooleanSupplier?
implement single method: getAsBooleanBooleanSupplier b1 = lambda functionboolean result = b1.getAsBoolean()
80
how would you use optionals and functional programming to only print an Optional value that is 3 in length ?
"Optional i = Optional.of(""1"");i.map(s -> """" + s).filter(x -> x.length() == 3).isPresent(System.out::print)"
81
how would you calculate the average of 3 animal name lengths using functional programming and collect()?
"Stream names = Stream.of(""lion"", ""bear"", ""flamingo"");Double result = names.collect(Collectors.averagingInt(String::length))"