大家好,谢谢大家的帮助。
我有一个Stream<String>
字符串可以像“ 1 + 5 * 2-4” // = 8的东西(如果我从左到右计算它可以)
这个操作没问题,但是我现在只尝试使用Streams,这意味着我只需要使用流操作,例如filter,reduce,collect ...
我尝试了过去6个小时,却一无所知。不允许建立列表并分析此方向的元素或其他内容。一个流操作或多个流操作必须直接给我最终结果。
有人有什么想法吗?
我最好的尝试是
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);
更新:我可能解释得很糟。最终结果必须提供流操作。在此流操作中,我们可以调用辅助方法。
工作解决方案,修正了错别字,这要归功于@ 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
。顺便说一句,不要忘记使用/
两次对字符进行转义\\
,因为它在正则表达式中具有特殊含义。
如果您真的坚持基于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;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句