map instead of switch

how to no use switch
 avatar
user_9487184
java
a year ago
1.4 kB
13
Indexable
Never
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collector;

public class Calculator {

    private enum Operation{
        SUM,MUL,DIV,SOTR
    }
    final static Map<Operation,BiConsumer<Integer,Integer>> calc = new HashMap<>(
        Map.of(
            Operation.SUM, (arg1,arg2)-> summ(arg1,arg2),
            Operation.SOTR, (arg1,arg2)-> sotr(arg1,arg2),
            Operation.MUL, (arg1,arg2)-> mul(arg1,arg2),
            Operation.DIV, (arg1,arg2)-> div(arg1,arg2)

        )
    );
    
    public static void main(String[] args) {
        int a = 3;
        int b = 10;
        calc.get(Operation.SOTR).accept(a,b);
        System.out.println(); 

        var l = List.of(List.of(1,2),List.of(3,2,1,20));
        var res = l.stream().flatMap((li)->li.stream()).map(x->x.toString()).toList();
   }

    private static  void div(Integer arg1, Integer arg2) {
        System.out.println(arg1/arg2);
    }

    private static  void mul(Integer arg1, Integer arg2) {
        System.out.println(arg1*arg2);
    }

    private static  void sotr(Integer arg1, Integer arg2) {
        System.out.println(arg1-arg2);
    }

    private static  void summ(Integer arg1, Integer arg2) {
        System.out.println(arg1+arg2);
    }
}