private static final List<NewArithmeticOperator> arithmeticOperators = List.of(new AdditionOperator(), new SubtractionOperator(), new MultiplicationOperator(), new DivisionOperator());
public static int arithmeticCalculate(int op1, int op2, String operator) {
return arithmeticOperators.stream()
.filter(arithmeticOperators -> arithmeticOperators.support(operator))
.map(arithmeticOperators -> arithmeticOperators.calculate(op1, op2))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("올바른 사칙 연산이 아닙니다."));
}
해당 코드는 Java에서 작성된 코드로, 주어진 두 개의 숫자 (op1
, op2
)와 연산자 (operator
)를 사용하여 사칙 연산을 수행하는 arithmeticCalculate
메소드를 포함하고 있습니다. 그러나 여기에서 중요한 것은 이 메소드가 사용하는 Java의 Stream API입니다.
주어진 예시에서 op1
과 op2
가 각각 2이고, operator
가 "*"일 경우 아래와 같이 동작합니다:
arithmeticOperators
리스트의 각 요소 (NewArithmeticOperator
타입의 객체들)에 대해 filter
를 수행합니다. 이 때 filter
조건은 각 객체의 support
메소드가 operator
와 일치하는지 여부입니다. 여기서는 통해 newAdditionOperator(), new SubtractionOperator(), new MultiplicationOperator(), new DivisionOperator()을 순서대로 확인합니다. operator
는 "*"이므로, MultiplicationOperator
객체만이 filter
조건을 만족하게 됩니다.
filter
를 통과한 객체 (MultiplicationOperator
)에 대해 map
연산을 수행합니다. map
연산은 calculate
메소드를 호출하여 op1
과 op2
의 곱셈 결과를 얻습니다. 여기서는 2 * 2로, 결과는 4가 됩니다.
findFirst
는 스트림에서 첫 번째 요소를 선택합니다. 이 경우, filter
를 통과한 유일한 요소가 MultiplicationOperator
이므로 이를 선택하게 됩니다.
orElseThrow
는 선택된 요소가 없는 경우 예외를 발생시킵니다. 그러나 이 예시에서는 MultiplicationOperator
가 성공적으로 선택되었으므로, 예외는 발생하지 않습니다.
따라서, arithmeticCalculate
메소드는 op1
과 op2
의 곱셈 결과인 4를 반환합니다. 만약 operator
가 리스트에 있는 사칙 연산자에 해당하지 않는다면, "올바른 사칙 연산이 아닙니다."라는 메시지와 함께 IllegalArgumentException
이 발생하게 됩니다.