工作解决方案,错别字更正,感谢@Turing85
Java-8 Stream-API 并不是万能的灵丹妙药,而且我看不到任何使用 lambda 表达式的简单解决方案。
我建议你坚持程序的方式去:
String string = "1+5*2-4";
String[] operator = a.split("[0-9]+");
String[] digits = a.split("[+-\\/*]");
int reduced = Integer.parseInt(digits[0]);
for (int i = 1; i < digits.length; i++) {
if (operator[i].equals("+")) { reduced += Integer.parseInt(digits[i]); }
else if (operator[i].equals("/")) { reduced /= Integer.parseInt(digits[i]); }
else if (operator[i].equals("*")) { reduced *= Integer.parseInt(digits[i]); }
else if (operator[i].equals("-")) { reduced -= Integer.parseInt(digits[i]); }
}
此解决方案仅简化为整数,无需检查输入和字符序列。 reduced 的数量导致8。顺便说一句,不要忘记用\\ 将/ 字符转义两次,因为它在Regex 中有特殊含义。
如果您真的坚持使用基于 Stream-API 的解决方案,它会给出相同的结果,那么您可以这样做:
String a = "1+5*2-4";
System.out.println(a);
String[] operator = a.split("[0-9]+");
String[] digits = a.split("[+-\\/*]");
final int[] index = {0};
int reduced = Stream.of(digits)
.mapToInt(Integer::parseInt)
.reduce(0, (int t, int u) ->
{
int result = Integer.parseInt(digits[0]);
int i = index[0];
if (operator[i].equals("+")) { result = t + u; }
else if (operator[i].equals("/")) { result = t / u; }
else if (operator[i].equals("*")) { result = t * u; }
else if (operator[i].equals("-")) { result = t - u; }
index[0]++;
return result;
});
我希望你现在可以比较这两个结果,看看哪一个在简洁性和可维护性方面胜出,在我看来,这比炫耀你在 Stream-API 和 lambda 表达式方面的表现更重要。但是,如果您挑战自己以了解有关 Stream-API 的更多信息,我建议您尝试寻找其他用例。 :)
编辑:此外,您应该将操作符数字处理隐藏到方法中:
public static int process(int identity, int t, int u, String[] array, int index) {
int result = identity;
if (array[index].equals("+")) { result = t + u; }
else if (array[index].equals("/")) { result = t / u; }
else if (array[index].equals("*")) { result = t * u; }
else if (array[index].equals("-")) { result = t - u; }
return result;
}
那么我可能会承认 Stream-API 不是一个糟糕的选择。
String a = "1+5*2-4";
System.out.println(a);
String operator[] = a.split("[0-9]+");
String digits[] = a.split("[+-\\/*]");
final int[] index = {0};
int reduced = Stream.of(digits).mapToInt(Integer::parseInt).reduce(0, (int t, int u) -> {
int result = process(Integer.parseInt(digits[0]), t, u, operator, index[0]);
index[0]++;
return result;
});