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}}== |
||
Up to Java 7, you have to define an interface for each type of function you want to use. |
|||
⚫ | |||
while the <code>IntToInt</code> is used to replace the array values. |
|||
<lang java>public class ArrayCallback7 { |
|||
⚫ | |||
interface IntConsumer { |
|||
void run(int x); |
void run(int x); |
||
} |
|||
} |
|||
⚫ | |||
⚫ | |||
int run(int x); |
|||
} |
|||
⚫ | |||
⚫ | |||
static void forEach(int[] arr, IntConsumer consumer) { |
|||
⚫ | |||
consumer.run(i); |
|||
} |
} |
||
} |
} |
||
⚫ | |||
static void update(int[] arr, IntToInt mapper) { |
|||
Or if you want to perform "map" - return an array of the results of function applications: |
|||
⚫ | |||
arr[i] = mapper.run(arr[i]); |
|||
} |
|||
} |
|||
public static void main(String[] args) { |
|||
⚫ | |||
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
|||
⚫ | |||
} |
|||
forEach(numbers, new IntConsumer() { |
|||
int[] result = new int[myIntArray.length]; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
result[i] = |
|||
} |
|||
⚫ | |||
update(numbers, new IntToInt() { |
|||
@Override |
|||
public int run(int x) { |
public int run(int x) { |
||
return x * x; |
return x * x; |
||
} |
} |
||
} |
}); |
||
forEach(numbers, new IntConsumer() { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
}); |
|||
} |
|||
}</lang> |
}</lang> |
||
Line 1,407: | Line 1,425: | ||
{{works with|Java|8}} |
{{works with|Java|8}} |
||
<lang java> |
<lang java>import java.util.Arrays; |
||
⚫ | |||
public class ArrayCallback { |
|||
⚫ | |||
⚫ | |||
public static void main(String[] args) { |
|||
⚫ | |||
} |
int[] myIntArray = {1, 2, 3, 4, 5}; |
||
⚫ | |||
int sum = Arrays.stream(myIntArray) |
|||
</lang> |
|||
.map(x -> { |
|||
⚫ | |||
System.out.println(cube); |
|||
return cube; |
|||
}) |
|||
⚫ | |||
System.out.println("sum: " + sum); |
|||
} |
|||
⚫ | |||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |