-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCollections.java
More file actions
60 lines (50 loc) · 1.55 KB
/
Collections.java
File metadata and controls
60 lines (50 loc) · 1.55 KB
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
package task;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Collections {
public static <X, Y> List<Y> map(Function1<? super X, Y> f, Iterable<X> a) {
List<Y> list = new LinkedList<>();
for (X x : a) {
list.add(f.apply(x));
}
return list;
}
public static <X> List<X> filter(Predicate<? super X> p, Iterable<X> a) {
List<X> list = new LinkedList<>();
for (X x : a) {
if (p.apply(x)) {
list.add(x);
}
}
return list;
}
public static <X> List<X> takeWhile(Predicate<? super X> p, Iterable<X> a) {
List<X> list = new LinkedList<>();
for (X x : a) {
if (!p.apply(x)) break;
list.add(x);
}
return list;
}
public static <X> List<X> takeUnless(Predicate<? super X> p, Iterable<X> a) {
return takeWhile(p.not(), a);
}
public static <X, Y> Y foldr(Function2<? super Y, ? super X, Y> f, Y base, Iterable<X> a) {
return myFoldr(f, base, a.iterator());
}
public static <X, Y> Y foldl(Function2<? super Y, ? super X, Y> f, Y base, Iterable<X> a) {
for (X x : a) {
base = f.apply(base, x);
}
return base;
}
private static <X, Y> Y myFoldr(Function2<? super Y, ? super X, Y> f, Y base, Iterator<X> a) {
if (!a.hasNext()) {
return base;
} else {
X x = a.next();
return f.apply(myFoldr(f, base, a), x);
}
}
}