Please review my Parser
class. Should I declare map outside of convToPosfixQueue
method?
class Parser {
private final Stack<String> tempStack = new Stack<>();
private final Queue<String> postfixQueue = new LinkedList<>();
public Parser(Queue<String> infixQueue) {
convToPosfixQueue(infixQueue);
}
public Parser() {
super();
}
interface ProcessingMethod {
void method(String token);
}
public Queue<String> convToPosfixQueue(Queue<String> infixQueue) {
Map<String, ProcessingMethod> methodMap = new HashMap<>();
methodMap.put("(", this::parseOpenBracket);
methodMap.put(")", this::parseCloseBracket);
methodMap.put("+", this::parseOperator);
methodMap.put("-", this::parseOperator);
methodMap.put("*", this::parseOperator);
methodMap.put("/", this::parseOperator);
infixQueue.stream().forEach(token -> {
if (!isNumber(token)) {
methodMap.get(token).method(token);
} else
parseNumber(token);
});
return collectParsedTokens();
}
private void parseOpenBracket(String token) {
tempStack.push(token);
}
private void parseCloseBracket(String token) {
while (!tempStack.empty()
&& !isOpenBracket(tempStack.lastElement())) {
postfixQueue.add(tempStack.pop());
}
tempStack.pop();
}
private void parseNumber(String token) {
postfixQueue.add(token);
}
private void parseOperator(String token) {
while (!tempStack.empty()
&& isOperator(tempStack.lastElement())
&& getPrecedence(token) <= getPrecedence(tempStack.lastElement())) {
postfixQueue.add(tempStack.pop());
}
tempStack.push(token);
}
private Queue<String> collectParsedTokens() {
while (!tempStack.empty()) {
postfixQueue.add(tempStack.pop());
}
return postfixQueue;
}
private boolean isNumber(String token) {
return token.matches("[-+]?\\d*\\.?\\d+");
}
private boolean isOpenBracket(String token) {
return token.equals("(");
}
private boolean isCloseBracket(String token) {
return token.equals(")");
}
private boolean isOperator(String token) {
String OPERATORS = "+-*/";
return OPERATORS.contains(token);
}
private byte getPrecedence(String token) {
if (token.equals("+") || token.equals("-")) {
return 1;
}
return 2;
}
}