Do Math With Lambda

To create a map of mathematical operations using lambda expressions in Java, you need to define BiFunction instances for each operation and use these to populate the results map. Here is the completed code:

import java.util.HashMap;

import java.util.Map;

import java.util.function.BiFunction;


class Answer {

    // Change these boolean values to control whether you see

    // the expected answer and/or hints

    static boolean showExpectedResult = false;

    static boolean showHints = false;


    // Create constants representing the four available math functions

    public static final String ADD = "ADD";

    public static final String SUBTRACT = "SUBTRACT";

    public static final String MULTIPLY = "MULTIPLY";

    public static final String DIVIDE = "DIVIDE";


    // Do mathematical calculations using lambda expressions

    public static Map<String, Float> calculate(float value1, float value2) {

        // Create 4 instances of the BiFunction interface referencing lambda expressions

        BiFunction<Float, Float, Float> add = (val1, val2) -> val1 + val2;

        BiFunction<Float, Float, Float> sub = (val1, val2) -> val1 - val2;

        BiFunction<Float, Float, Float> mul = (val1, val2) -> val1 * val2;

        BiFunction<Float, Float, Float> div = (val1, val2) -> val1 / val2;


        // Map object for holding the results

        Map<String, Float> results = new HashMap<>();


        // Populate the map here with the results of the 4 math operations

        results.put(ADD, add.apply(value1, value2));

        results.put(SUBTRACT, sub.apply(value1, value2));

        results.put(MULTIPLY, mul.apply(value1, value2));

        results.put(DIVIDE, div.apply(value1, value2));


        return results;

    }


    public static void main(String[] args) {

        float value1 = 10.0f;

        float value2 = 5.0f;


        Map<String, Float> results = calculate(value1, value2);


        System.out.println("Results:");

        System.out.println(ADD + ": " + results.get(ADD));

        System.out.println(SUBTRACT + ": " + results.get(SUBTRACT));

        System.out.println(MULTIPLY + ": " + results.get(MULTIPLY));

        System.out.println(DIVIDE + ": " + results.get(DIVIDE));

    }

}


Comments

Popular posts from this blog

Transform values with a stream

Collections Framework

Inspect a collection