大家好,谢谢你们的帮助。
我有一个Stream<String>,其中一个字符串可以是"1+5*2-4“//= 8(如果我从左到右计算它就可以了)。
这个操作没有问题,但是我现在尝试用Streams only.It来完成它,这意味着我只需要使用流操作,比如过滤器、减少、收集.
我试了六个小时却不知道。它不允许在这个方向上建立列表和分析元素或其他东西。流操作或多个流操作必须直接给出最终结果。
有人有什么想法吗?
我最大的努力就是
Stream<String> numbers = myList.stream().filter(s ->
Character.isDigit(s.charAt(0)));
List<String> operands = myList.stream().filter(s ->
!Character.isDigit(s.charAt(0))).collect(Collectors.toList());
String result = numbers.reduce((a, b) -> {
int iA = Integer.parseInt(a);
int iB = Integer.parseInt(b);
String operation = operands.get(0);
operands.remove(0);
return calc(iA,iB,operation);
}).get();
System.out.println(result);更新:我可能解释得很糟糕。最终结果必须交付流操作。在这个流操作中,我们可以调用助手方法。
发布于 2018-05-28 19:24:59
工作解决方案,由于@Turing85而更正了排版
Java-8Stream-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的解决方案(它提供了相同的结果),那么您可以这样做:
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和lambda表达式更重要。但是,如果您为了更多地了解Stream而挑战自己,我建议您尝试找到其他用例。:)
编辑:此外,您应该将操作符数字处理隐藏到一个方法中:
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并不是一个糟糕的选择。
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;
}); https://stackoverflow.com/questions/50572329
复制相似问题