This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 326
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit a72acb9
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
|
||
interface StringChecker { boolean checkString(String s); } | ||
|
||
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(StringChecker sc, List<String> list) { | ||
List<String> result = new ArrayList<>(); | ||
for(String s: list) { | ||
if(sc.checkString(s)) { | ||
result.add(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)); | ||
index2 += 1; | ||
} | ||
return result; | ||
} | ||
|
||
|
||
} |