我目前有此代码:
AtomicInteger counter = new AtomicInteger(0);
return IntStream.range(0, costs.length)
.mapToObj(i -> new int[]{costs[i][0]-costs[i][1], i})
.sorted(Comparator.comparingInt(d -> d[0]))
.mapToInt(s ->
counter.getAndIncrement() < costs.length/2 ? costs[s[1]][0] : costs[s[1]][1]
)
.sum();
在这里,我计算数组中两个元素的差异,然后对其进行排序,最后我需要独立处理两个一半。
有没有比使用
AtomicInteger
作为计数器更好的方法呢?是否有某种方法(例如mapToIntWithIndex
)可在JDK内访问(不在外部库中)? python中是否有类似zip()
的东西,我可以将索引与流一起加入?如果没有,有没有计划将其添加到下一个Java版本中? 最佳答案
这不是执行此操作的可靠方法。地图中使用的函数的Streams API makes it clear不应为有状态的。
如果流操作的行为参数是有状态的,则流管道结果可能不确定或不正确。
如果使用有状态函数,则它可能看起来有效,但是由于根据文档未使用有状态函数,因此该行为在技术上是未定义的,并且可能会在Java的 future 版本中中断。
收集到一个列表,然后处理列表的两半:
List<int[]> list = /* your stream up to and including the sort */.collect(toList());
int sum = list.subList(0, half ).stream().mapToInt(s -> costs[s[1]][0]).sum()
+ list.subList(half, list.size()).stream().mapToInt(s -> costs[s[1]][1]).sum();
实际上,我很想将其编写为for循环,因为我发现它更容易使用:
int sum = 0;
for (int[][] s : list.subList(0, half)) sum += costs[s[1]][0];
for (int[][] s : list.subList(half, list.size())) sum += costs[s[1]][1];
关于java - 使用Java Stream-独立处理两半流,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62169605/