简体   繁体   中英

How can i remove an element in a string list in java?

As u can see i wanna delete or remove the ingrediant which equals my ingredientid from my SplitedIgrediants list, i've tried with remove or delete but it's appear an error. So how can i do to delete this ingredient elemant please from my list in JAVA.

        String ingredientid = request.getParameter("id");
        DbHandler dbsplt = new DbHandler();
        for (String ingrediant : SplitedIngrediants) {
            if (ingrediant.equals(ingredientid)) {
                //HERE REMOVE THE ingredient from SplitedIngrediants list
            }

You cannot remove elements from a Collection while iterating on it (you will get some ConcurrentModificationException ) except if you manually declare the iterator and use iterator.remove() .

Example :

List<Integer> list = new ArrayList<Integer>();

list.add(3);
list.add(4);
list.add(5);

Iterator<Integer> it = list.iterator();
Integer current;
while (it.hasNext()) {
    current = it.next();
    if(current.equals(4)) {
        it.remove();
    }
}

Ouput :

[3, 5]

The reason behind that is that the "foreach" construction internally creates an iterator. The aim of the iterator is to ensure that each element of the iterable is visited exactly once. So if you add/remove elements from the iterable without using the iterator methods, the iterator can no longer fulfil its task.

2nd option : while iterating on the list, make a list of the items to delete and delete them after iterating.

Try this:

String ingredientid = request.getParameter("id");
SplitedIngrediants.removeAll(Collections.singleton(ingredientid));

Example code:

public static void main(String args[]) {
        List<String> l = new ArrayList<String>();
        l.add("first");
        l.add("first");
        l.add("second");

        String ingredientid = "first";

        l.removeAll(Collections.singleton(ingredientid));

        System.out.println(l);
    }

With SplitedIngrediants is a String array try this:

public static void main(String args[]) {
    String[] SplitedIngrediants = new String[] { "first", "first", "second" };

    String ingredientid = "first";

    List<String> NewSplitedIngrediants = new ArrayList<>();
    for (String ingrediant : SplitedIngrediants) {
        if (!ingrediant.equals(ingredientid)) {
            NewSplitedIngrediants.add(ingrediant);
        }
    }
    SplitedIngrediants = new String[NewSplitedIngrediants.size()];
    SplitedIngrediants = NewSplitedIngrediants.toArray(SplitedIngrediants);
    for (String ingrediant : SplitedIngrediants) {
        System.out.println(ingrediant);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM