Skip to content

Commit 2e86a41

Browse files
committed
add collect utility
1 parent 00f22f9 commit 2e86a41

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package it.aboutbits.springboot.toolbox.util;
2+
3+
import lombok.NonNull;
4+
import org.springframework.data.util.Streamable;
5+
6+
import java.util.Collection;
7+
import java.util.List;
8+
import java.util.Objects;
9+
import java.util.Set;
10+
import java.util.function.Function;
11+
import java.util.stream.Collectors;
12+
import java.util.stream.Stream;
13+
14+
/**
15+
* This is a collection of tools to simply collect a property to a new collection or stream.
16+
* The common usage would, for example, be to collect the ids of all items in a list to a set.
17+
* <p>
18+
* The returned collections are unmodifiable.
19+
*/
20+
public final class CollectUtil {
21+
private CollectUtil() {
22+
}
23+
24+
public static <T, R> Set<R> collectToSet(@NonNull Collection<T> items, @NonNull Function<T, R> mapper) {
25+
return items.stream()
26+
.map(mapper)
27+
.filter(Objects::nonNull)
28+
.collect(Collectors.toUnmodifiableSet());
29+
}
30+
31+
public static <T, R> Set<R> collectToSet(@NonNull Streamable<T> items, @NonNull Function<T, R> mapper) {
32+
return items.stream()
33+
.map(mapper)
34+
.filter(Objects::nonNull)
35+
.collect(Collectors.toUnmodifiableSet());
36+
}
37+
38+
public static <T, R> Set<R> collectToSet(@NonNull Stream<T> items, @NonNull Function<T, R> mapper) {
39+
return items
40+
.map(mapper)
41+
.filter(Objects::nonNull)
42+
.collect(Collectors.toUnmodifiableSet());
43+
}
44+
45+
public static <T, R> List<R> collectToList(@NonNull Collection<T> items, @NonNull Function<T, R> mapper) {
46+
return items.stream()
47+
.map(mapper)
48+
.filter(Objects::nonNull)
49+
.toList();
50+
}
51+
52+
public static <T, R> List<R> collectToList(@NonNull Streamable<T> items, @NonNull Function<T, R> mapper) {
53+
return items.stream()
54+
.map(mapper)
55+
.filter(Objects::nonNull)
56+
.toList();
57+
}
58+
59+
public static <T, R> List<R> collectToList(@NonNull Stream<T> items, @NonNull Function<T, R> mapper) {
60+
return items
61+
.map(mapper)
62+
.filter(Objects::nonNull)
63+
.toList();
64+
}
65+
66+
public static <T, R> Stream<R> collectToStream(@NonNull Collection<T> items, @NonNull Function<T, R> mapper) {
67+
return items.stream()
68+
.map(mapper)
69+
.filter(Objects::nonNull);
70+
}
71+
72+
public static <T, R> Stream<R> collectToStream(@NonNull Streamable<T> items, @NonNull Function<T, R> mapper) {
73+
return items.stream()
74+
.map(mapper)
75+
.filter(Objects::nonNull);
76+
}
77+
78+
public static <T, R> Stream<R> collectToStream(@NonNull Stream<T> items, @NonNull Function<T, R> mapper) {
79+
return items
80+
.map(mapper)
81+
.filter(Objects::nonNull);
82+
}
83+
}

0 commit comments

Comments
 (0)