forked from ucsd-cse15l-f22/lab3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ListExamples.java
55 lines (47 loc) · 1.45 KB
/
ListExamples.java
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
import java.util.ArrayList;
import java.util.List;
interface StringChecker { boolean checkString(String s); }
class StringImp implements StringChecker{
public boolean checkString(String s){
return true;
}
}
class ListExamples {
// Returns a new list that has all the elements of the input list for which
// the StringChecker returns true, and not the elements that return false, in
// the same order they appeared in the input list;
static List<String> filter(List<String> list, StringChecker sc) {
List<String> result = new ArrayList<>();
for(String s: list) {
if(sc.checkString(s)) {
result.add(0, s);
}
}
return result;
}
// Takes two sorted list of strings (so "a" appears before "b" and so on),
// and return a new list that has all the strings in both list in sorted order.
static List<String> merge(List<String> list1, List<String> list2) {
List<String> result = new ArrayList<>();
int index1 = 0, index2 = 0;
while(index1 < list1.size() && index2 < list2.size()) {
if(list1.get(index1).compareTo(list2.get(index2)) < 0) {
result.add(list1.get(index1));
index1 += 1;
}
else {
result.add(list2.get(index2));
index2 += 1;
}
}
while(index1 < list1.size()) {
result.add(list1.get(index1));
index1 += 1;
}
while(index2 < list2.size()) {
result.add(list2.get(index2));
index1 += 1;
}
return result;
}
}