I want to change the values of a collection of unknown type. I found java.util.Collections.replaceAll, but that works only for Lists. I helped myself creating a new new Collection and adding the changed elements.
if (o instanceof Collection) {
Collection<Object> newCollection = (Collection<Object>) o.getClass().newInstance();
for (Iterator<Object> it = ((Collection<Object>)o).iterator(); it.hasNext(); ) {
newCollection.add(doSomethingWith(it.next()));
}
return newCollection;
}
But I liked to return the same List as result. Any ideas?
Collections.replaceAll(new ArrayList(yourCollection), old, new);. If you want to return it, just save the new list to a variable before doing the replacement.