Collections, Streams and Filters Flashcards

1
Q

What is a predicate and where can we use it?

A

Predicate is an expression that evaluates to a boolean value, often used for filtering operations. This interface has a single abstract method

boolean test(T t)

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

removeIf is a method of which class?

A

Collection

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

how can we use the removeIf method?

A

Passing a Predicate argument

boolean removeIf(Predicate super {{E}} filter)

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

What does the filter method returns?

A

Returns a stream consisting of elements that match the specified predicate

Stream filter(Predicate super {{T}} predicate)

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

What is the Consumer interface represent?

A

An operation

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

What does the Consumer interface accepts and returns and where is it used?

A

Accepts a single input argument and returns no result. Used in forEach methods in Streams and List

void accept(T t)

as it it a functional interface, can be represented by a lambda expression

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

The Stream.forEach takes which parameter?

A

void forEach(Consumer super {{T}} action)

this method is a terminal operation, consuming the stream. Behaviour non-deterministic

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

From which class is the forEach method in List interface inherited from?

A

The Iterable interface, and it is a default method

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

What is the difference between the forEach method in List and Stream?

A

Stream is nondeterministic while the forEach of List is deterministic.

Their method signature is the same

void forEach(Consumer super {{T}} action)

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

How can a Stream be created?

A

Stream method can be created by a static method in Stream interface, or by a stream creation method invoked on a data source. Stream can only be operated once
The source should not be modified while the stream si being processed

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

What is the stream pipeline comprised of?

A

Comprised of a data source (method such as of() and generate()), intermediate operations(map, filter, distinct, sorted) and a single terminal operation(sum, collect, forEach, reduce)

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

What does intermediate operations returns?

A

They return a new stream, these operations are all lazy and only triggered when the terminal operation is initialized

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

Stream stream = Stream.of(“Whizlabs”);
stream.forEach(s -> sout(s)).forEach(s -> sout(s)

what happens when the code is compiled and executed

A

compilation fails because the forEach method cannot be chained

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

Stream stream = Stream.of(“Whizlabs”);

stream. filter(s -> s.startsWith(“ J”));
stream. forEach(s -> System.out.println(s));

What happens when this code is compiled and executed?

A

An exception is thrown because once you use the stream, it cannot be re-used. For it to work you would have to chain the foreEach method or re-declare the stream ex.

stream = stream.filter(s -> s.startsWith(“ J”));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
public class Data {
	private int var;
	public Data(int var) {
		this.var = var;
	}
	public int getVar() {
		return var;
	}
}

Collection collection = new ArrayList();

collection. add(new Data(1));
collection. add(new Data(2));
collection. removeIf(d -> d.getVar() % 2 == 0);

what is the output of this code?

A

When a collection is created with raw types, its elements are considered to be of type Object, hence “d” does not have the getVar() method and it fails to compile

to compile it would have to be:

Collection collection = new Arraylist<>()

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

When to use a reference method?

A

a reference method can be used in the place of a lambda expression if the expression body does nothing but invoke an existing method

syntax:

::

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

What are the four kinds of reference methods?

A
  • Reference to static method
  • Reference to an instance method of an arbitrary object of a particular type
  • Reference to an instance method of a particular object
  • Reference to a constructor
18
Q

What is the difference between a static reference method and a Instance method of an arbitrary Object?

A

Reference to a static method, the current object is passed as an argument to the method

Reference to an instance method of an arbitrary object of a particular type, method is called on the current object

19
Q

What are the three ways of creating ArrayList objects?

A

ArrayList() -> constructs an empty list with the initial capacity of ten

ArrayList(int initialCapacity) -> constructs an empty list with the initial capacity

ArrayList(Collection extends E) c) -> constructs a list containing elements of the specified collection, in order they are returned by the collections iterator

20
Q

In which order is the TreeSet implemented?

A

Are ordered using their natural ordering or by a Comparator provided at creation time, depending on which constructor is used

21
Q

About the TreeSet class, what does these methods do?

ceiling
floor
headSet
tailSet

A
TreeSet treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(5);
treeSet.add(6);

ceiling: returns the least element in the set greater than or equal to the specified element.

Ex. treeSet.ceiling(4); // 5

floor: returns the greatest element in the set less than or equal to the specified element

Ex. treeSet.floor(4); //2

headSet: returns a view of the portion of the set whose elements are less than the specified element

treeSet.headSet(4) // 1,2

tailSet: returns a view of the portion of the set whose elements are greater than the specified element

treeSet.tailSet(4) // 5,6

22
Q

About the ArrayDeque methods:

What does:

1) peek*
2) pool*
3) offer*

  • can be first or last

do?

A

1) retrieves but does not remove the first/last element of the deque
2) retrieves and removes the first/last element of the deque
3) inserts the specified element at the beginning or the end of the deque

Queue{Integer} queue= new ArrayDeque{}()
queue.offer(10)
queue.offer(4)
queue = [10,4]

Queue{Integer} stack= new ArrayDeque{}()
stack.push(10)
stack.push(4)
stack.push(5)
queue = [5,4,10]
23
Q

What is the method if the Comparable interface defines?

A

int compareTo(T object)

24
Q

What is the method that the Comparator interface defines?

A

int compare(T object1, T object2)

25
Q

What is the difference between the comparable and the comparator interface?

A

Comparable is internal, while Comparator is external

26
Q

What are some ways of declaring Stream sources?

A
  1. You can use range or iterate factory methods in the IntStream interface

IntStream.rage(1,6)
2. You can use the stream() method

Arrays.stream(new int[] { 1, 2, 3, 4, 5})

  1. We can also create streams using factories and builders. The of() method is a factory method in the Stream interface

Stream.of(1,2,3,4,5)
Stream.of( new Integer[]{1,2,3,4,5}
Stream.builder().add(1).add(2).build()

27
Q

What are the example of some intermediate Operations?

A

filter, map, distinct, sorted, peek, limit

28
Q

How do we use the peek method?

A

For debugging purposes

Stream.of(1, 2, 3, 4, 5)
 .peek(i -> System.out.printf("%d ", i))
 .map(i -> i * i)
 .peek(i -> System.out.printf("%d ", i))
 .count();
29
Q

What is the difference between pop and poll?

A

They do the same, but pop throws exception if the queue is empty

  • They remove the first element
30
Q

What does computerIfPresent do?

A
  • Calls a bi function if the requested key is found
  • if the mapping function is called and returns null, the keyword is removed from the map

default V computeIfPresent(K key,
BiFunction{? super K, ? super V, ? extends V} remappingFunction) {

31
Q

What is an upper bound?

A

It’s when you specify (? extends Field) means that the argument can be any Field or subclass of Field

32
Q

What is an lower bound?

A

Is when you specify (? super Field), it can be any Field or superclass or field

33
Q

What are the four types of method references?

A
  • static methods

Consumer{List{Integer}} methodRef1 = Collection:sort;
Consumer{List{Integer}} lambda1 = l -> Collection.sort(l)

  • calling an instance method on a specific instance

String str = “abc”
Predicate{String} methodRef2 = str:startsWith
Predicate{String} lambda2 = s -> str.startsWith(s)

  • call an instance method without knowing the instance in advance

Predicate{String} methodRef3 = String:isEmpty
Private{String} lambda3 = str -> str.isEmpty();

  • Constructor reference, uses new instead of a method
Supplier{ArrayList} methodRef4 = ArrayList::new
Supplier{ArrayList} lambda4 = () -> new ArrayList()
34
Q

What are the primitive Streams?

A

IntStream -> used for primitive types int, short, byte and char

LongStream -> Used for primitives type long

DoubleStream -> used for double and float

35
Q

Given:

a) IntStream range = IntStream.ranged(1,6) and
b) IntStream rangeClosed = IntStream.rangedClosed(1,5)

what does it return?

A

a) 1,2,3,4,5

b) ,1,2,3,4,5

36
Q

What are the Stream Intermediate Operations?

A
  • filter
  • distinct
  • limit
  • skip
  • map
  • flatMap
  • sorted
37
Q

What are the Stream termina operations?

A
  • count() : long
  • min/max : Optional{T}
  • findAny/findFirst : Optional{T}
  • anyMatch : boolean
  • allMatch: boolean
  • noneMatch : boolean
  • forEach: void
  • reduce
  • collect
38
Q

given:

Deque{Integer} d = new ArrayDeque{};

what is the difference between add(e) and push(e)?

difference between offer(e) and offerFirst(e)?

what does the remove() method do?

A
  • add(e) is a queue method that adds element to the end of the queue
  • push is a stack method that adds to the front
  • offer adds to the end of the queu, offerFirst adds to the front
  • remove is a queue method that removes from the front
39
Q

What happens if you call getAsDouble|Long|Int on a emptyOptionalDouble|Long|Int?

A

throws java.util.NoSuchElementException

40
Q

Which interfaces does java.util.NavigableMap extend directly or indirectly?

A

java. util.Map

java. util.SortedMap