Skip to content

Instantly share code, notes, and snippets.

@joshiraez
Created June 9, 2019 12:55
Show Gist options
  • Save joshiraez/348398df048a5135a7f49f8467d4432c to your computer and use it in GitHub Desktop.
Save joshiraez/348398df048a5135a7f49f8467d4432c to your computer and use it in GitHub Desktop.
package behaviouralSwitch.structureAlternative;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BinaryOperator;
public class DataStructureCalculator {
private static Map<Character, BinaryOperator<Integer>> operations =
new HashMap<Character, BinaryOperator<Integer>>() {{
put('+', (a,b) -> a+b);
put('-', (a,b) -> a-b);
put('x', (a,b) -> a*b);
put('/', (a,b) -> a/b);
}};
public int calculate(char op, int a, int b) {
if (!operations.containsKey(op)) throw new IllegalArgumentException();
return operations.get(op).apply(a,b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment