4. Java 8: Collection operations with Lambda Flashcards

1
Q
How could you create a stream of Employee objects given the following class:
class Employee {
// Field and getters/setters omitted
Employee(String name);
}
A

Stream.of(new Employee(“Jan”), new Employee(“Henk”));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
Given a Stream of Employee objects create a list of Integer objects.
class Employee {
// Field and getters/setters omitted
Employee(String name);
}
A
Stream employees = Stream.of(new Employee("Jan"), new Employee("Henk"));
Stream names = employees.map(Employee::getName);
Stream lenghts = names.map(String::lenght);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the primitive specialized Stream interfaces?

A
  • IntStream
  • DoubleStream
  • LongStream
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the Stream methods for mapping a Stream to a primitive specialized stream?

A
  • mapToInt
  • mapToLong
  • mapToDouble
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Primitive specialized streams come with some convenience methods, what are these methods?

A

min()
max()
sum()
average()

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

What is the difference between the findFirst and findAny method?

A

The findAny methods behavior is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations;

While findFirst while always return the first element (or an empty optional)

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

Using a Stream of String objects, use the anyMatch method to see if the name “Henk” is present.

A

Stream names = Stream.of(“Jan”, “Henk”, “Benny”);

boolean test = names.anyMatch(e -> “Henk”.equalsIgnoreCase(e)); // True

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

Using a Stream of String objects, use the allMatch method to determine if all names start with a “B”.
And use the noneMatch to determine that none of the names start with a “A”

A

Stream names = Stream.of(“Bob”, “Benny”);

names. allMatch(e -> e.startsWith(“B”)); // True
names. nonMatch(e -> e.startsWith(“A”)); // True

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

How would one create a empty Optional?

A

Optional.empty();

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

How would one create a Optional from a non-null object?

A

Optional.of(T);

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

How would one create a Optional from a object that might be NULL?

A

Optional.ofNullable(T);

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

What is the result of the following?
String s = null;
Optional optional = Optional.from(s);
System.out.println(optional.isPresent());

A

NullPointerException

Optional.of can only be used for non-null objects. If you want to wrap a (potential) null object use the Optional.ofNullable(T) factory method.

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

How can you retrieve the value of a Optional?

A

optional.get();

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

What is the difference between
Optional.orElse(T other)
or
Optional.orElseGet(Supplier extends T> other)

A

orElseGet is lazy

The supplier code is only executed when the Optional is really empty (it’s lazy). Whit orElse you really need to provide a object that is already created.

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

Give a Optional wrapping a String how would one write the code to get the value but if it doesn’t exist it will throw a IllegalArgumentException?

A
String s = null;
Optional opt = Optional.ofNullable(s);
String value = opt.orElseThrow(() -> new IllegalArgumentException());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Given a Optional wrapping a String how would I print the actual value only if it’s not null?

A

String s = “Hello World”;
Optional opt = Optional.of(s);
s.ifPresent(v -> System.out.println(v)));

17
Q

What is the Optional method to check if a value is not null?

A

Optional.isPresent();

18
Q

Given the following Stream:
Stream names = Stream.of(“Bob”, “Benny”);
How would you write the code to retrieve the shortest and the longest name?

A

Optional minName = names.min(Comparator.comparing(item -> item.length()));
Optional maxName =
names.max(Comparator.comparing(item -> item.length()));

19
Q

Given the following Stream:
Stream names = Stream.of(“Bob”, “Benny”);
How would you write the code that calculates the number of items?

A

long count = names.count();

20
Q

What specialized primitive stream can be used to store short primitive?

A

IntStream

short, char, byte and boolean can all be stored in a IntStream because they will fit.

21
Q

What spcialized primitive stream can be used to store a float prmitive?

A

DoubleStream

A float primitive can be stored in a DoubleStream because it can fit in a double.

22
Q

How would one create a IntStream with the following numbers (1, 5, 10) and calculate the min and max?

A

IntStream numbers = IntStream.of(1,5,10);
IntOptional min = numbers.min();
IntOptional max = numbers.max();

23
Q

Given a Stream of strings how can it be sorted using the default sorting?

A

strings.sorted().collect(Collectors.toList());

24
Q

The stream.sorted() method sorts objects in a Stream. What does the sorted method require from a Object to be sorted? And what will happen if that Object does’nt meet that requirement?

A

The object should implement the Comparable interface.

If the object doesn’t implement this interface it will throw a ClassCastException.

25
Q

Using the sorted(Comparator c) method and comparators how can we sort the following stream of Strings first on length and then on the string itself?
Stream names = Stream.of(“Bob”, “Benny”, “Annie”);

A

Comparator c1 = Comparator.comparing(e -> e.length());
Comparator c2 = (e1, e2) -> e1.compareTo(e2);

names.sorted(c1.thenComparing(c2))
.collect(Collectors.toList());

26
Q

What are the Collectors methods to collect the results of a stream in a List or Set?

A

toList()

toSet()

27
Q

What are the Collectors methods available besides toList and toSet?

A

Collectors.averagingDouble(ToDoubleFunction super T> mapper);
Will collect the average for a stream, for example: stream().collect(Collectors.averagingDouble(s -> s.length());

Collectors.groupingBy(Function super T, ? extends K> classifier);
A group by operation grouping the elements according to the classification function and returning the result in a map.
For example: Map groupedBy = stream.collect(Collectors.groupingBy(Employee::getDepartement));

Collectors.joining()
Joins all Objects in a Stream using the toString() method into a single String.
For example:
String joinedString = str.map(Employee::getName).collect(Collectors.joining);

Collectors.partitioningBy(Predicate super T> predicate)
Will group all elements into a map where the predicate either returns true or false.
For Example:
Map> = str.collect(Collectors.partitioningBy(e -> “Management”.equals(“e.getDepartment()));