-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathLambdas.java
75 lines (67 loc) · 2.7 KB
/
Lambdas.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.kernel.commons;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collector;
/**
* Helper class which provides various methods to work with lambdas.
*/
public class Lambdas {
private Lambdas() {
}
/**
* Provides an identity function which permits to "touch" the element for which it was called.
* <p>
* This is designed to be used with {@link java.util.Optional} like this:
* {@code return Optional.of("Test").map(Lambdas.touch(s -> System.out.println(s)))}
*
* @param consumer the lambda used to "touch" (use) each parameter
* @param <T> the type of the elements accepted by the consumer
* @return an identity function which also applies the <tt>consumer</tt> on each parameter
*/
public static <T> Function<T, T> touch(Consumer<T> consumer) {
return t -> {
consumer.accept(t);
return t;
};
}
/**
* Can be used to group a given stream by identity and count the occurrences of each entity.
*
* @param <K> the type of the key by which the values are grouped
* @return a Collector which can be supplied to {@link java.util.stream.Stream#collect(java.util.stream.Collector)}.
*/
public static <K> Collector<K, Map<K, Integer>, Map<K, Integer>> groupAndCount() {
return Collector.of(HashMap::new,
Lambdas::increment,
Lambdas::unsupportedBiOperation,
Function.identity(),
Collector.Characteristics.IDENTITY_FINISH);
}
private static <K> void increment(Map<K, Integer> map, K value) {
map.put(value, map.computeIfAbsent(value, k -> 0) + 1);
}
/**
* Can be used as lambda for unsupported BiOperations.
* <p>
* This is intended to be a dummy parameter (e.g. for <tt>Collector.of</tt>. It will always throw
* an <tt>UnsupportedOperationException</tt> if invoked.
*
* @param <O> the type of objects for which the operation is to be used
* @param a the first parameter of the binary operation
* @param b the second parameter of the binary operation
* @return this method will never return a value as an <tt>UnsupportedOperationException</tt> is thrown
* @throws java.lang.UnsupportedOperationException always thrown by this method
*/
public static <O> O unsupportedBiOperation(O a, O b) {
throw new UnsupportedOperationException();
}
}