Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Strings of given length from an ArrayList?

We are given a list of words in the form of an ArrayList as follows:

 public ArrayList<String> getListOfStrings(){
     ArrayList<String> list = new ArrayList<String>();
     list.add("This");
     list.add("is");
     list.add("an");
     list.add("exercise");
     list.add("to");
     list.add("illustrate");
     list.add("the");
     list.add("use");        
     list.add("of");
     list.add("ArrayLists");        
     list.add(".");
     return list;
    }

How do I write a method that removes all words in that list (i.e. all the objects in the ArrayList) that have the length "len" entered by the user?

I already wrote a method that lists all the words of length "len" entered by the user, and it works, it's as follows:

public ArrayList<String>getWordsWithLength(int len, ArrayList<String> lijst){
    ArrayList<String> list = new ArrayList<String>();
    for(String woord: lijst){
        if(woord.length()==len){
            list.add(woord);
        }
    }
    return(list);

}

But as a beginner in java, I'm stuck on how to remove the words of length "len". Please help! (I am under the impression that you start by removing them from the end of the list, back-to-front as it were)

like image 895
user2895102 Avatar asked Oct 18 '13 14:10

user2895102


People also ask

How do I remove a string from an ArrayList?

remove() Method. Using the remove() method of the ArrayList class is the fastest way of deleting or removing the element from the ArrayList. It also provides the two overloaded methods, i.e., remove(int index) and remove(Object obj).

How do I remove a string from a list of strings in Java?

Java List remove() method is used to remove elements from the list.

How do I remove a string from an array in Java?

Answer: Java does not provide a direct method to remove an element from the array. But given an index at which the element is to be deleted, we can use ArrayList to remove the element at the specified index. For this, first, we convert the array to ArrayList and using the remove method we remove the element.

What does .remove do in Java ArrayList?

The . remove() method is used for removing specified elements from instances of the ArrayList class.


1 Answers

The way your currently iterating through the list wont allow you to remove it with an exception but an iterator would.

Iterator<String> it = list.iterator();
while(it.hasNext()) {
 if([Condition]) {
   it.remove();
  }
}
like image 67
AbstractChaos Avatar answered Nov 03 '22 18:11

AbstractChaos