Problem:
Given an array of strings, return a new List (e.g. an ArrayList) where all the strings of the given length are omitted. See wordsWithout() below which is more difficult because it uses arrays.
wordsWithoutList({"a", "bb", "b", "ccc"}, 1) → {"bb", "ccc"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 3) → {"a", "bb", "b"}
wordsWithoutList({"a", "bb", "b", "ccc"}, 4) → {"a", "bb", "b", "ccc"}
Solution:
public List wordsWithoutList(String[] words, int len) { ArrayList al = new ArrayList(); for (int i = 0; i < words.length; i++) { if (words[i].length() != len) al.add(words[i]); } return al; }
ArrayList list = new ArrayList();
ReplyDeletefor (String s: words){
if(s.length()!=len)
list.add(s);
}return list;
public List wordsWithoutList(String[] words, int len) {
ReplyDeletereturn Arrays.stream(words).filter(x -> x.length() != len).collect(Collectors.toList());
}
public List wordsWithoutList(String[] words, int len) {
ReplyDeletereturn Arrays.stream(words)
.filter(x -> x.length() != len)
.collect(Collectors.toList());
}
public List wordsWithoutList(String[] words, int len) {
ReplyDeleteList list = new ArrayList<>();
for (final String s: words){
if(s.length()!=len) {
list.add(s);
}
}
return list;
}
public List wordsWithoutList(String[] words, int len) {
ReplyDeleteList list = new ArrayList<>(Arrays.asList(words));
list = list.removeIf(s -> s.length() == len);
return list;
}
Solution using lambda functional filtering.