diff options
Diffstat (limited to 'store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java')
-rw-r--r-- | store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java b/store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java new file mode 100644 index 00000000..21b0a9df --- /dev/null +++ b/store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java | |||
@@ -0,0 +1,72 @@ | |||
1 | package org.eclipse.viatra.solver.data.util; | ||
2 | |||
3 | import java.util.Iterator; | ||
4 | import java.util.NoSuchElementException; | ||
5 | import java.util.function.Function; | ||
6 | import java.util.function.Predicate; | ||
7 | |||
8 | public final class CollectionsUtil { | ||
9 | private CollectionsUtil() { | ||
10 | throw new UnsupportedOperationException(); | ||
11 | } | ||
12 | |||
13 | public static <S,T> Iterator<T> map(Iterator<S> source, Function<S, T> transformation) { | ||
14 | return new Iterator<T>() { | ||
15 | |||
16 | @Override | ||
17 | public boolean hasNext() { | ||
18 | return source.hasNext(); | ||
19 | } | ||
20 | |||
21 | @Override | ||
22 | public T next() { | ||
23 | return transformation.apply(source.next()); | ||
24 | } | ||
25 | }; | ||
26 | } | ||
27 | |||
28 | public static <S,T> Iterable<T> map(Iterable<S> source, Function<S, T> transformation) { | ||
29 | return (()->map(source.iterator(),transformation)); | ||
30 | } | ||
31 | |||
32 | public static <T> Iterator<T> filter(Iterator<T> source, Predicate<T> condition) { | ||
33 | return new Iterator<T>() { | ||
34 | T internalNext = move(); | ||
35 | boolean internalHasNext; | ||
36 | |||
37 | private T move() { | ||
38 | internalHasNext = source.hasNext(); | ||
39 | if(internalHasNext) { | ||
40 | internalNext = source.next(); | ||
41 | } | ||
42 | while(internalHasNext && !condition.test(internalNext)) { | ||
43 | internalHasNext = source.hasNext(); | ||
44 | if(internalHasNext) { | ||
45 | internalNext = source.next(); | ||
46 | } | ||
47 | } | ||
48 | return internalNext; | ||
49 | } | ||
50 | |||
51 | @Override | ||
52 | public boolean hasNext() { | ||
53 | return internalHasNext; | ||
54 | } | ||
55 | |||
56 | @Override | ||
57 | public T next() { | ||
58 | if(!internalHasNext) { | ||
59 | throw new NoSuchElementException(); | ||
60 | } else { | ||
61 | T result = internalNext; | ||
62 | move(); | ||
63 | return result; | ||
64 | } | ||
65 | } | ||
66 | }; | ||
67 | } | ||
68 | |||
69 | public static <T> Iterable<T> filter(Iterable<T> source, Predicate<T> condition) { | ||
70 | return (()->filter(source.iterator(),condition)); | ||
71 | } | ||
72 | } | ||