How to iterate over lambda functions in java?

  • A+
Category:Languages

I was able to do it in python and my python code is:

signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}  a = 5 b = 3 for i in signs.keys():     print(signs[i](a,b)) 

And the output is :

8 2 

How do I do this same thing in java through HashMap?

 


You can use BiFunction in this case Like so :

BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;//lambda a, b : a + b BiFunction<Integer, Integer, Integer> sub = (a, b) -> a - b;//lambda a, b : a - b  //then create a new Map which take the sign and the corresponding BiFunction //equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} Map<String, BiFunction> signs = Map.of("+", add, "-", sub);  int a = 5;//a = 5 int b = 3;//b = 3  //loop over the sings map and apply the operation signs.values().forEach(v-> System.out.println(v.apply(a, b))); 

Outputs

8 2 

Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so :

Map<String, BiFunction> signs = new HashMap<>(); signs.put("+", add); signs.put("-", sub); 

Ideone demo

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: