简体   繁体   中英

Java add/remove at the same loop without ConcurrentModificationException

I have a following Java code:

if (value instanceof Collection) {
    Collection collection = (Collection) value;
    Collection updatedObjects = new ArrayList<>();
    for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
        Object object = iterator.next();
        if (object instanceof String) {
            iterator.remove();
            updatedObjects.add(StringUtils.wrapInSingleQuotes((String) object));
        } else if (object instanceof Date) {
            iterator.remove();
            updatedObjects.add(((Date) object).getTime());
        }
    }
    collection.addAll(updatedObjects);
}

Is it possible to rewrite this code in a more efficient way in order to avoid new ArrayList allocation ? If so, please show an example.

Having Collection of different types is bad practice, anyway you can use Java 8 streams:

return collection.stream().map(object -> {
        if (object instanceof String) {
            return StringUtils.wrapInSingleQuotes((String) object);
        } else if (object instanceof Date) {
            return ((Date) object).getTime();
        }
    }).collect(Collectors.toList());

Also you can just avoid calling iterator.remove() and before the last line write

collection.clear();
collection.addAll...

If you want to update the value of the variable collection because is a parameter varialble, for example you can follow the logic in java.util.List.sort implementation.

    Object[] updatedObjects = collection.toArray();
    //fill the array updatedObjects 
    ListIterator<E> i = collection.listIterator();//this works only if collection is a list
    for (Object e : updatedObjects ) {
        i.next();
        i.set((E) e);
    }

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