james
james

Reputation: 13

How to remove strings that contain at least an uppercase letter in them from an ArrayList<String>?

So, I have an ArrayList called totalListOfWords. It contains a mixed of words from which has both lower and upper case letters in it. I want to remove all the words that contain upper case letter in them. Below is what I have.

I have a helper method called containsUpperCaseLetter. It basically checks whether a string contain an upper case letter in it.

Then I loop through my totalListOfWords using for loop and check each word in the list whether it contains an upper case letter. If so, I try to remove it. But it only remove some words. May be I am choosing the wrong type? Help please.

public class TextProcessor() {
   ArrayList<String> totalListOfWords = new ArrayList<String>();
   
   totalListOfWords.add("The");
   totalListOfWords.add("Project");
   totalListOfWords.add("Gutenberg");
   totalListOfWords.add("eBook");
   totalListOfWords.add("of");
   totalListOfWords.add("Pride");
   totalListOfWords.add("and");
   totalListOfWords.add("Prejudice");
   totalListOfWords.add("by");
   totalListOfWords.add("Jane");
   totalListOfWords.add("Austen");

   public void processText() {
      for (int i = 0; i < totalListOfWords.size(); i++) {
         if(containsUpperCaseLetter(totalListOfWords.get(i))){
            totalListOfWords.remove(i);
         }
      }
      System.out.println(totalListOfWords);  
   }   

   public boolean containsUpperCaseLetter(String s){
      for(int i = 0; i < s.length(); i++){
          if(Character.isUpperCase(s.charAt(i))){
              return true;
          }
      }
      return false;
   }

   public static void main(String[] args) {
      TextProcessor t1 = new TextProcessor();
      t1.processTextAtURL(url1);
   }
}

Upvotes: 1

Views: 517

Answers (1)

shmosel
shmosel

Reputation: 50726

When you remove the element at index i, the next element is now at i instead of i+1. You would have to decrement i so it checks the same index again:

for (int i = 0; i < totalListOfWords.size(); i++) {
    if(containsUpperCaseLetter(totalListOfWords.get(i))){
        totalListOfWords.remove(i);
        i--;
    }
}

Or you can use an iterator instead:

for (Iterator<String> iter = totalListOfWords.iterator(); iter.hasNext();) {
    if (containsUpperCaseLetter(iter.next())) {
        iter.remove();
    }
}

Or you can skip the whole loop altogether:

totalListOfWords.removeIf(word -> containsUpperCaseLetter(word));

Upvotes: 4

Related Questions