-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathListHelper1.java
More file actions
36 lines (29 loc) · 911 Bytes
/
ListHelper1.java
File metadata and controls
36 lines (29 loc) · 911 Bytes
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
import java.util.List;
import java.util.ArrayList;
public class ListHelper1 {
public interface MapFunction<A, B> {
public B apply(A input);
}
public static <A, B> List<B> map(List<A> list, MapFunction<A, B> func) {
List<B> mappedList = new ArrayList<>();
for (A elem : list) {
mappedList.add(func.apply(elem));
}
return mappedList;
}
public static void main(String[] args) {
List<String> words = new ArrayList<>();
words.add("hello");
words.add("goodbye");
words.add("hi");
List<Integer> lengths = map(words, new MapFunction<String, Integer>() {
public Integer apply(String str) {
return str.length();
}
});
// print out lengths 5, 7, 2
for (int length : lengths) {
System.out.println(length);
}
}
}