-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mapping.java
74 lines (65 loc) · 2.18 KB
/
Mapping.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
package com.yunikov.commons;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Defines a mapping between source and the target class.
*
* @param <SOURCE> source class for mapping
* @param <TARGET> target class for mapping
* @since 1.8
*/
@FunctionalInterface
public interface Mapping<SOURCE, TARGET> {
/**
* Maps the source object to target object.
*
* @param source source object
* @return created target object
*/
TARGET map(final SOURCE source);
/**
* @see #mapToStream(Stream, Function) mapToStream
*/
default Stream<TARGET> mapToStream(final Stream<SOURCE> sources) {
return sources.map(this::map);
}
/**
* Maps the source stream to a target stream.
*
* @param sources stream of source objects
* @param createMethod method for creating a target object
* @return stream of target objects
*/
default Stream<TARGET> mapToStream(final Stream<SOURCE> sources, final Function<SOURCE, TARGET> createMethod) {
return sources.map(createMethod);
}
/**
* @see #mapToList(Stream, Function) mapToStream
*/
default List<TARGET> mapToList(final Stream<SOURCE> sources) {
return mapToStream(sources).collect(Collectors.toList());
}
/**
* Maps the source stream to a target list.
*
* @param sources stream of source objects
* @param createMethod method for creating a target object
* @return list of target objects
*/
default List<TARGET> mapToList(final Stream<SOURCE> sources, final Function<SOURCE, TARGET> createMethod) {
return mapToStream(sources, createMethod).collect(Collectors.toList());
}
/**
* Maps the source stream to a target map.
*
* @param sources stream of source objects
* @param createMethod method for creating a target object
* @return map of target objects
*/
default Map<SOURCE, TARGET> mapToMap(final Stream<SOURCE> sources, final Function<SOURCE, TARGET> createMethod) {
return sources.collect(Collectors.toMap(obj -> obj, createMethod));
}
}