Java > AP-1 > wordsWithoutList (CodingBat Solution)

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;
}

5 comments:

  1. ArrayList list = new ArrayList();
    for (String s: words){
    if(s.length()!=len)
    list.add(s);
    }return list;

    ReplyDelete
  2. public List wordsWithoutList(String[] words, int len) {
    return Arrays.stream(words).filter(x -> x.length() != len).collect(Collectors.toList());
    }

    ReplyDelete
  3. public List wordsWithoutList(String[] words, int len) {
    return Arrays.stream(words)
    .filter(x -> x.length() != len)
    .collect(Collectors.toList());
    }

    ReplyDelete
  4. public List wordsWithoutList(String[] words, int len) {
    List list = new ArrayList<>();
    for (final String s: words){
    if(s.length()!=len) {
    list.add(s);
    }
    }
    return list;
    }

    ReplyDelete
  5. public List wordsWithoutList(String[] words, int len) {
    List list = new ArrayList<>(Arrays.asList(words));
    list = list.removeIf(s -> s.length() == len);
    return list;
    }

    Solution using lambda functional filtering.

    ReplyDelete