Re: How do you change all elements in a Collection at the same time?
phillip.s.powell@gmail.com wrote:
That will walk through an array and perform change on every element in
the array.
$array = array(1, 2, 3, 4, 5);
@array_walk($array, create_function('&$a', 'return ($a + 1);')); //
WILL RETURN (2, 3, 4, 5, 6)
For a one off, you could write it explicitly as:
List<Integer> values = Arrays.asList(new Integer[] {
1, 2, 3, 4, 5
});
for (
ListIterator<Integer> iter = values.listIterator();
Integer value = iter.next();
) {
iter.set(value + 1);
}
System.out.println(values);
To abstract the 'array walking' takes a bit more work:
public interface Transform<T> {
T transform(T value);
}
....
public <T> static void transform(
List<T> values, Transform<T> transform
) {
for (
ListIterator<T> iter = values.listIterator();
T value = iter.next();
) {
iter.set(transform.transform(value));
}
}
....
List<Integer> values = Arrays.asList(new Integer[] {
1, 2, 3, 4, 5
});
transform(values, new Transform<Integer>() {
public Integer transform(Integer value) {
return value+1;
}
});
System.out.println(values);
I have used List instead of Collection, because Collection doesn't
provide a ListIterator and it's not an entirely sensible operation to
perform on a set anyway.
As you can see, abstracting loops is not a particularly natural thing to
do in Java. After splitting the method, my example is only one line
shorter and indents three levels instead of one. The inner class can
only reference final variables of the enclosing method. So it isn't done
very often in Java, at the moment.
There are various proposals to make things simpler in Java 7. These will
allow something like:
// BGGA
transform(values) {
Integer value => value+1
}
transform(values, { Integer value => value+1 });
// CICE (possibly without the <Integer>).
transform(values, Transform<Integer>(Integer value) {
return value+1;
});
// My favourite:
transform(values, new()(Integer value) {
return value+1;
});
Tom Hawtin