Re: How do you change all elements in a Collection at the same time?
phillip.s.powell@gmail.com wrote:
In my native language, PHP, we have a function called array_walk()
http://www.php.net/manual/en/function.array-walk.php
That will walk through an array and perform change on every element in
the array.
I've studied the Collections within Java so far and this seems like the
right way to do it (Collections.replaceAll(List list, Object oldVal,
Object newVal)):
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#replaceAll(java.util.List,%20java.lang.Object,%20java.lang.Object)
But looking at the API does not tell me how to do a function-based
"array_walk" like we can so easily do in PHP:
<?
$array = array(1, 2, 3, 4, 5);
@array_walk($array, create_function('&$a', 'return ($a + 1);')); //
WILL RETURN (2, 3, 4, 5, 6)
?>
So how do I do this in Java?
Thanx
Phil
Java doesn't exactly have closures, so its hard to do stuff like what
your asking.. However, what you really want is:
Replacing "doChange" with whatever is appropriate.
You COULD make a utility class that does this for you:
public interface Transformer {
Object transform(Object o);
}
public class ListWalker {
public static void walk(List myList, Transformer transformer) {
ListIterator iterator = myList.listIterator();
while (iterator.hasNext()) {
iterator.set( transformer.transform(iterator.next()) );
}
}
Now you can call:
ListWalker.walk(myList, new Transformer() {
public Object transform(Object o) {
return new Integer(((Integer)o).intValue() + 1);
}
});
Ick... Did I just write that?
Well, you can't do little "tricks" with Java like you can in PHP, but
don't worry about that too much.