假设我有一个字符串数组,我想过滤该数组,反转流的顺序,然后将流组合成一个字符串。
包含此内容以反转流的输出顺序是不好的做法吗?:
**.sorted(Comparator.comparing(n -> counter[0]++)) **
(使用名为 counter 的外部 int[],我可以反转流中的数组,而不必先退出流)。
例如,代码可能如下所示:
String[] strs = {“Sally”, “Sold”, “Seashells”, “By”, “The”, “Seashore”};
int[] counter = {0};
return Arrays.stream(strs).filter(n -> n.charAt(0)==“S”).sorted(Comparator.comparing(n -> counter[0]++)).collect(Collectors.joining(“ “));
所以代码返回的是“Seashore Seashells Sold Sally”。我知道这种反转流顺序的方法是有效的,因为我在 leetcode 和 codewars 等地方的有趣练习问题上多次使用过它,没有出现错误。
这是多么糟糕的做法?
我认为这是不好的做法,但有时它让我的生活变得如此轻松。我觉得我必须少打字和思考。
在最好的情况下排序是
nLogn
。由于您必须将它们连接起来才能获取字符串,因此反向连接它们将需要相对较少的处理并完成相同的事情。这是一种具有多种可能性的方法。
String s = Arrays.stream(strs).filter(n -> n.charAt(0) == 'S')
.reduce("", (a,b)-> b + " " + a).trim();
System.out.println(s);
打印
Seashore Seashells Sold Sally
注意:要比较字符,它是
== 'S'
而不是 == "S"