Je pouvais le faire en Python et mon code Python est:
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))
Et le résultat est:
8 2
Comment puis-je faire la même chose en Java avec HashMap?
Vous pouvez utiliser BinaryOperator
dans ce cas comme BinaryOperator
:
BinaryOperator add = (a, b) -> a + b;//lambda a, b : a + b BinaryOperator sub = (a, b) -> a - b;//lambda a, b : a - b // Then create a new Map which take the sign and the corresponding BinaryOperator // equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} Map> 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)));
Les sorties
8 2
Note pour Map.of("+", add, "-", sub);
J’utilise Java 10. Si vous n’utilisez pas Java 9+, vous pouvez append des éléments à votre carte de la manière suivante:
Map> signs = new HashMap<>(); signs.put("+", add); signs.put("-", sub);
Ideone démo
Comme déjà indiqué par @Boris the Spider et @Holger dans les commentaires, il est préférable d’utiliser IntBinaryOperator
pour éviter la boxe, à la fin votre code peut ressembler à ceci:
// signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b} Map signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b); int a = 5; // a = 5 int b = 3; // b = 3 // for i in signs.keys(): print(signs[i](a,b)) signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));
Créez vous-même une belle, typesafe, enum
:
enum Operator implements IntBinaryOperator { PLUS("+", Integer::sum), MINUS("-", (a, b) -> a - b); private final Ssortingng symbol; private final IntBinaryOperator op; Operator(final Ssortingng symbol, final IntBinaryOperator op) { this.symbol = symbol; this.op = op; } public Ssortingng symbol() { return symbol; } @Override public int applyAsInt(final int left, final int right) { return op.applyAsInt(left, right); } }
Vous voudrez peut-être un lambda qui renvoie double
plutôt que int
pour les autres opérateurs.
Maintenant, déposez-le simplement dans une Map
:
final var operators = Arrays.stream(Operator.values()) .collect(toMap(Operator::symbol, identity()));
Pour votre exemple cependant, vous n’avez pas besoin d’une Map
du tout:
Arrays.stream(Operator.values()) .mapToInt(op -> op.applyAsInt(a,b)) .forEach(System.out::println);
En utilisant:
import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap;