-
Notifications
You must be signed in to change notification settings - Fork 906
Expand file tree
/
Copy pathOperator.java
More file actions
46 lines (38 loc) · 1.35 KB
/
Operator.java
File metadata and controls
46 lines (38 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Collections;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public enum Operator {
PLUS("+", (first, second) -> first + second),
MINUS("-", (first, second) -> first - second),
MULTIPLY("*", (first, second) -> first * second),
DIVIDE("/", (first, second) -> {
if (second == 0) {
throw new IllegalArgumentException();
}
return first / second;
});
private static final Map<String, Operator> OPERATOR_MAP =
Collections.unmodifiableMap(Stream.of(values())
.collect(Collectors.toMap(operator -> operator.getSymbol(), operator -> operator)));
private final String symbol;
private final BiFunction<Integer, Integer, Integer> operation;
Operator(String symbol, BiFunction<Integer, Integer, Integer> operation) {
this.symbol = symbol;
this.operation = operation;
}
public static Operator findOperator(String symbol) {
Operator operator = OPERATOR_MAP.get(symbol);
if (operator == null) {
throw new IllegalArgumentException();
}
return operator;
}
public String getSymbol() {
return symbol;
}
public int operate(int first, int second) {
return operation.apply(first, second);
}
}