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
Q

How can you thrown an exception using a Supplier if Optional value is not present? What happens if value is present?

A

anOptional.orElseThrow(Supplier s)value returned

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

What is stream in Java?

A

a sequence of data

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

What is a stream pipeline?

A

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
28
Q

what are the 3 parts of a stream pipeline?

A

source - where stream comes fromintermediary operations - transforms stream into anotherterminal operation - actually produces a result

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

how many times can stream result from a terminal operation be used?

A

once

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

how many times can stream result from a intermediary operation be used?

A

as many times as you want

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

when are intermediary vs terminal operations called?

A

intermediary - lazy evaluation - not called until terminal operation runterminal - run when method called

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

does an intermediary or a terminal operation return a stream type?

A

intermediary - yesterminal - no

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

can there be multiple intermediary or terminal operations in a pipeline?

A

multiple intermediarysingle terminal

34
Q

are intermediary or terminal operations required in a pipeline?

A

intermediary - noterminal - yes

35
Q

how do you create a stream of 0, 1, and multiple elements?

A

Stream.empty()Stream.of(1)Stream.of(1, 2, 3)- remember this takes var args, so you can list 1 or more elements

36
Q

how do you create a stream from a list? how do you create a stream that can have intermediary operations run in parallel?

A

list.stream();list.parallelStream();

37
Q

how would you create an infinite stream of random Double values and print them out?

A

Stream doubles = Streams.generate(Math::random);doubles.forEach(System.out::println);

38
Q

how would you create a stream that has a seed or starting value and processes that value?

A

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

39
Q

What is a reduction? what is an example of a reduction?

A

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
Q

What happens if count() is called on an infinte stream?

A

the thread hangs - since it’s counting to infinity

41
Q

What do min() and max() do if called on finite vs. infinite stream? are these reductions?

A

finite - return min and max Optional valuesinfinite - thread hangsyes, reductions since they return a single value and process all values in stream

42
Q

What do findAny() and findFirst() do?

A

findAny() - returns an Optional with any valuefindFirst() - returns an Optional with the first value in the stream

43
Q

Why would you use findAny() over findFirst()?

A

findAny() works with parallel streams

44
Q

are findAny() and findFirst() reductions? do they terminate?

A

they are NOT reductions since they may not process the entire stream sequence before returningthey do terminate, they work with infinite streams

45
Q

what do allMatch() and noneMatch() do for infinite vs finite streams?

A

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
Q

what does anyMatch() do for infinite vs finite streams?

A

infinite - could terminate if a match is foundfinite - always terminates whether match is found or not

47
Q

once a Stream method is run on a given stream - allMatch(), count(), etc. - can we reuse that stream for a different result?

A

no, stream results can only be used once

48
Q

what does the stream method forEach() do and what does it return?

A

it loops through the Stream elements- hangs for infinite streams- returns void

49
Q

Can you call forEach directly on a Stream or a Collection?

A

both

50
Q

can Streams use the traditional for loop since they can use forEach?

A

no, streams do not implement IterableforEach for streams is actually a terminal operator for streams, not a loop

51
Q

“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”

A

“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
Q

write a reduction to multiply all of the Integer objects in a stream

A

Stream integers = Stream.of(1, 2, 3, 4);Integer result = integers.reduce(1, (x,y) -> x*y);

53
Q

when does reduce() return an optional?

A

if no identity is specified

54
Q

what is returned for reduce() for the following 1) empty stream 2) single element 3) multiple elements

A

1) empty Optional2) single element3) reduction applied

55
Q

what is special about collect()?

A

it is a mutable reduction

56
Q

what is a mutable reduction?

A

more efficient because the same mutable object is used while accumulating

57
Q

what are two method signatures for Stream.collect()?

A

R collect(Supplier supplier, BiConsumer accumulator, BiConsumer Combiner) R collect(Collector super T>, A, R> collector

58
Q

“how would you use collect(3 params) to return a StringBuilder object from a Stream that contains the letters in the word ““happy””?”

A

“Stream s = Stream.of(““h””, ““a””, ““p””, ““p””, ““y””);StringBuilder result = s.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);”

59
Q

“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()?”

A

used for processing parallel collections - if there were multiple data collections, it would be responsible for merging collections together

60
Q

“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””?”

A

“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
Q

what are the Collectors static methods used for?

A

commonly used scenarios for Streams.collect()

62
Q

how do intermediary operations differ from terminal operations when dealing with infinite streams?

A

intermediary operations return an infinite stream and no hung threads - intermediary only deals with one element at a time

63
Q

what does filter() do?

A

“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
Q

what does distinct() do?

A

“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
Q

what do skip() and limit() do?

A

both return streamsskip(int m) - returns stream after skipping first m elementslimit(int n) - returns max size by taking first n elements

66
Q

what does map() do?

A

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
Q

“how would you return the lengths of this stream using map? Stream s = Stream.of(““hello””, ““from””, ““the””, ““other””, ““side);”

A

“Stream s = Stream.of(““hello””, ““from””, ““the””, ““other””, ““side);s.map(String::length).forEach(System.out::println);// prints 54354”

68
Q

what is flatMap() used for?

A

“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
Q

“does this compile? Stream s = Stream.of(““a””, ““b””); s.sorted(Comparator::reverseOrder);”

A

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
Q

what’s the difference between queue peek() and stream peek()?

A

queue - only takes a look at the top elementstream - takes a look at every element as it passes by the pipeline

71
Q

can/should peek() modify the underlying stream data?

A

it shouldn’t, but Java doesn’t prevent you from doing it

72
Q

how would you use streams to print alphabetically the first 2 names in a stream that are 4 char long?

A

“List names = Arrays.asList(““Abby””, ““Barry””, ““Charlie””, ““Dean””, ““Evan””);names.stream().filter(x -> x.length() == 4).sorted().limit(2).forEach(System.out::println);”

73
Q

What are the 3 types of primitive streams?

A

IntStream - byte, short, int, charLongStream - longDoubleStream - double, float

74
Q

how do you use generate() and iterate() for a stream?

A

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
Q

how do you print a int 1-5 using range() and rangeClosed()

A

IntStream.range(1, 6)IntStream.rangeClosed(1, 5)

76
Q

How do you map from one stream type to another stream type?

A

mapTo[stream type here]mapping from any stream type to DoubleStream:objStream.mapToDouble(lambda for mapping);

77
Q

how do you map from one stream type to the same stream type?

A

objStream.map(lambda for mapping)

78
Q

What does IntStream.summaryStatistics return?

A

IntStream ints = Intstream.empty()IntSummaryStatistics s = ints.summaryStatistics();useful when you need several calculations from a stream- min- max- average- size- # elements

79
Q

how do you use a BooleanSupplier?

A

implement single method: getAsBooleanBooleanSupplier b1 = lambda functionboolean result = b1.getAsBoolean()

80
Q

how would you use optionals and functional programming to only print an Optional value that is 3 in length ?

A

“Optional i = Optional.of(““1””);i.map(s -> “””” + s).filter(x -> x.length() == 3).isPresent(System.out::print)”

81
Q

how would you calculate the average of 3 animal name lengths using functional programming and collect()?

A

“Stream names = Stream.of(““lion””, ““bear””, ““flamingo””);Double result = names.collect(Collectors.averagingInt(String::length))”