Friday, 4 September 2015

Removing elements from collections in java

in this tutorial lets discuss how to remove objects from collections list,Maps for the tutorial uses Array List

everybody knows how to iterate over a list or map my  .even though lots of way are there my favorite was for each. to iterate over a List of String

for(String iter:listname){

}
 so if we try to modify that is add or modify while iterating over it will throw concurrent modification exception So how to modify a collection while we iterate over it


ok  here we have a list

    

List<String> database = new ArrayList<String>();
        database.add("mysql");
        database.add("oracle");
        database.add("postgrade");
        database.add("mongodb");
        database.add("couchdb");
 there is two ways to remove a element while iterating over it 
1. iterating for loop backwards and removing them

for (int i = database.size() - 1; i >= 0; i--) {
            System.out.println("inside for loop" + database.get(i));
            if (database.get(i).equals("mongodb")) {
                System.out.println("sorry bitches you dont belong here you need to be kicked out");
                database.remove(i);
            }
        }
2nd way using the iterator

while (iterator.hasNext()) {
            String dbname = iterator.next();
            System.out.println("the iterator element is" + dbname);
            if (dbname.equals("couchdb")) {
                System.out.println("YOU too dont belong here you too will be kicked out");
                iterator.remove();
            }
        }

and the output








No comments:

Post a Comment