How to apply a callback to an array (apply a function to each element) in Java

2 Answers

0 votes
import java.util.function.IntUnaryOperator;

public class CallbackProgram {

    // Map function: applies a callback to each element and returns a new array
    // Takes an array
    // Takes a callback
    // Applies the callback to each element
    // Returns a new array
    public static int[] map(int[] arr, IntUnaryOperator callback) {
        int[] result = new int[arr.length];

        // Loop through the array and apply the callback
        for (int i = 0; i < arr.length; i++) {
            result[i] = callback.applyAsInt(arr[i]);
        }

        return result;
    }

    // callback: double the number
    public static int doubleValue(int x) {
        return x * 2;
    }

    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20};

        // Apply the callback using a method reference
        int[] doubled = map(numbers, CallbackProgram::doubleValue);

        // Print results
        for (int n : doubled) {
            System.out.println(n);
        }
    }
}



/*
run:

10
20
30
40

*/

 



answered Mar 20 by avibootz
0 votes
import java.util.function.IntUnaryOperator;

public class CallbackProgram {

    // in‑place version
    public static void forEach(int[] arr, IntUnaryOperator callback) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = callback.applyAsInt(arr[i]);
        }
    }

    // callback: double the number
    public static int doubleValue(int x) {
        return x * 2;
    }

    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20};

        // Apply the callback using a method reference
        forEach(numbers, CallbackProgram::doubleValue);

        // Print results
        for (int n : numbers) {
            System.out.println(n);
        }
    }
}



/*
run:

10
20
30
40

*/

 



answered Mar 20 by avibootz
...