Apply a callback to an array: Difference between revisions

Content added Content deleted
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(→‎{{header|Java}}: rewrite code to provide reusable components)
Line 1,372: Line 1,372:
=={{header|Java}}==
=={{header|Java}}==


As of the current version of Java, you have to define an interface for each type of function you want to use. The next version of Java will introduce function types.
Up to Java 7, you have to define an interface for each type of function you want to use.
The <code>IntConsumer</code> performs an action (which doesn't return anything) on an array of ints,
while the <code>IntToInt</code> is used to replace the array values.


<lang java>public class ArrayCallback7 {
So if you want to perform an action (which doesn't return anything) on an array of int's:


<lang java>interface IntToVoid {
interface IntConsumer {
void run(int x);
void run(int x);
}
}


interface IntToInt {
for (int z : myIntArray) {
new IntToVoid() {
int run(int x);
}
public void run(int x) {

System.out.println(x);
static void forEach(int[] arr, IntConsumer consumer) {
for (int i : arr) {
consumer.run(i);
}
}
}.run(z);
}
}</lang>


static void update(int[] arr, IntToInt mapper) {
Or if you want to perform "map" - return an array of the results of function applications:
for (int i = 0; i < arr.length; i++) {
arr[i] = mapper.run(arr[i]);
}
}


public static void main(String[] args) {
<lang java>interface IntToInt {
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int run(int x);
}


forEach(numbers, new IntConsumer() {
int[] result = new int[myIntArray.length];
public void run(int x) {
for (int i = 0; i < myIntArray.length; i++) {
System.out.println(x);
result[i] =
new IntToInt() {
}
});

update(numbers, new IntToInt() {
@Override
public int run(int x) {
public int run(int x) {
return x * x;
return x * x;
}
}
}.run(myIntArray[i]);
});

forEach(numbers, new IntConsumer() {
public void run(int x) {
System.out.println(x);
}
});
}
}</lang>
}</lang>


Line 1,407: Line 1,425:
{{works with|Java|8}}
{{works with|Java|8}}


<lang java> int sum1 = Arrays.stream(myIntArray)
<lang java>import java.util.Arrays;

.map(y_ -> {
public class ArrayCallback {
int x_ = y_ * y_ * y_;

out.println(x_);
public static void main(String[] args) {
return x_;
})
int[] myIntArray = {1, 2, 3, 4, 5};

.reduce(0, (il, ir) -> il + ir); // <-- could substitute .sum() for .reduce(...) here.
int sum = Arrays.stream(myIntArray)
</lang>
.map(x -> {
int cube = x * x * x;
System.out.println(cube);
return cube;
})
.reduce(0, (left, right) -> left + right); // <-- could substitute .sum() for .reduce(...) here.
System.out.println("sum: " + sum);
}
}</lang>


=={{header|JavaScript}}==
=={{header|JavaScript}}==