aboutsummaryrefslogtreecommitdiffstats
path: root/store/src/main/java/org/eclipse/viatra/solver/data/util/CollectionsUtil.java
blob: 21b0a9df02d3182304f5ffd1fca0ccfa767f1133 (plain) (blame)
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
package org.eclipse.viatra.solver.data.util;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Predicate;

public final class CollectionsUtil {
	private CollectionsUtil() {
		throw new UnsupportedOperationException();
	}
	
	public static <S,T> Iterator<T> map(Iterator<S> source, Function<S, T> transformation) {
		return new Iterator<T>() {

			@Override
			public boolean hasNext() {
				return source.hasNext();
			}

			@Override
			public T next() {
				return transformation.apply(source.next());
			}
		};
	}
	
	public static <S,T> Iterable<T> map(Iterable<S> source, Function<S, T> transformation) {
		return (()->map(source.iterator(),transformation));
	}
	
	public static <T> Iterator<T> filter(Iterator<T> source, Predicate<T> condition) {
		return new Iterator<T>() {
			T internalNext = move();
			boolean internalHasNext;
			
			private T move() {
				internalHasNext = source.hasNext();
				if(internalHasNext) {
					internalNext = source.next();
				}
				while(internalHasNext && !condition.test(internalNext)) {
					internalHasNext = source.hasNext();
					if(internalHasNext) {
						internalNext = source.next();
					}
				}
				return internalNext;
			}

			@Override
			public boolean hasNext() {
				return internalHasNext;
			}

			@Override
			public T next() {
				if(!internalHasNext) {
					throw new NoSuchElementException();
				} else {
					T result = internalNext;
					move();
					return result;
				}
			}
		};
	}
	
	public static <T> Iterable<T> filter(Iterable<T> source, Predicate<T> condition) {
		return (()->filter(source.iterator(),condition));
	}
}