Maikel
Maikel

Reputation: 41

Remove multiple items from ArrayList

I want to remove multiple items from arraylist.

this is the list:

String1-1, String5, String6, String1-2, String5, String6, String1-3, String5, String6

I want to remove String1- from the list. But because not all the String1- have the same end, they are not removed. So list.remove("String1-") is not working.

The question is: How to remove the multiple items from arraylist when the end of the string i want to remove is not the same.

Upvotes: 1

Views: 7455

Answers (2)

allprog
allprog

Reputation: 16780

For future reference, here is a solution with Google Guava.

Some setup code to create the list from the question's string:

String stringsString = "String1-1, String5, String6, String1-2, String5, String6, String1-3, String5, String6";
String[] stringsArray = stringsString.split(", ");
Iterable<String> stringsList = Arrays.asList(stringsArray);

And now filter out the unneeded items:

Iterable<String> filtered = Iterables.filter(stringsList, new Predicate<String>() {
    @Override
    public boolean apply(String input) {
        return !input.startsWith("String1-");
    }
});

This simple routine creates a new Iterable that contains only the elements that you specified. The beauty of this is that it is executed lazily (evaluated only when you really want to use it) and it does not modify the original collection. Making your software state immutable (unmodifiable) is in most cases the best you can do. Handling mutable collections is hard and they are often the cause of software errors.

Upvotes: 1

devrobf
devrobf

Reputation: 7213

There is no single method that will do this, but you can do it quite easily if you iterate over the ArrayList and use the String.startsWith method to test whether the string starts with "String1-".

Here is an example. Note that I have used an iterator because it makes removing things from arrays much easier than if you use a for loop.

Iterator<String> it = arrayList.iterator();
while (it.hasNext() ) {
   String value = it.next();
   if (value.startsWith("String1-") ) {
     it.remove();
   }
}

Upvotes: 9

Related Questions