Home > Software design >  How to remove a specific String from a String ArrayList
How to remove a specific String from a String ArrayList

Time:04-15

I have an ArrayList that contains a bunch of words each in their own cell that come from a file. Some of those words are complete word like "physicist, water, gravity". However, other words are just letters that got split throughout the process of the program. For example, "it's" became "it" and "s". As such, I want to remove all of the single letter words except "I" and "A" because these are actual words.

This is the code I have for now:

for(int i=0;i<dictionnary.size();i  ) {
            if(dictionnary.get(i).compareToIgnoreCase("I")!=0||dictionnary.get(i).compareToIgnoreCase("A")!=0||dictionnary.get(i).length()==1){
                dictionnary.remove(i);
            }
    }

Where dictionnary is my ArrayList. However, when I print out the content of my arrayList the "s" from it's remains. I also know that there was originally a word "E" that got removed throughout the process above. I'm confused as to why the "S" remains and how to fix it.

From my understanding this code goes through the ArrayList and checks if the length of the case is 1 (which is the case for all single letter words) as well as checking if that case is a case of "I" or "A" regardless of if it is capitalized or not. It then removes the cases that don't correspond to the "I" or "A".

CodePudding user response:

Consider using the Collection Iterator for safe removal of elements during iteration.

for (Iterator<String> iter = dictionary.iterator() ; iter.hasNext() ; ) {
  String word = iter.next();
  if (word.length() == 1 
      && !"I".equals(word)
      && !"A".equalsIgnoreCase(word)) {
    iter.remove();
  }
}

CodePudding user response:

My suggestion is the following:

You can use removeIf in a next way.

removeIf takes a predicate.

public static void main(String[] args) {
    List<String> dictionary =  new ArrayList<>();
    dictionary.add("I");
    dictionary.add("A");
    dictionary.add("p");
    dictionary.add("its");
    dictionary.add("water");
    dictionary.add("s");
    Integer sizeRemove =1;
    dictionary.removeIf(
            word ->
            !"I".equals(word)
            && !"A".equalsIgnoreCase(word)
            && word.length() == sizeRemove
    );
    System.out.println(dictionary);
}

The output is the following: [I, A, its, water]

Reference: https://www.programiz.com/java-programming/library/arraylist/removeif

CodePudding user response:

Use iterators instead. Let's say you have a list of (1,2,3,4,5) and you want to remove the numbers 2 and 3. You start looping through and get to the second element 2. Here your i is 1. You remove that element and go to i=2. What you have now is (1,3,4,5). Since i=2, you have missed one element.

And that's the reason you should use iterators instead. Refer to @vsfDawg answer.

  • Related