java - Java 流减少
问题描述
我有以下示例数据集,我想根据方向的值使用 Java 流 api 转换/减少
Direction int[]
IN 1, 2
OUT 3, 4
OUT 5, 6, 7
IN 8
IN 9
IN 10, 11
OUT 12, 13
IN 14
至
Direction int[]
IN 1, 2,
OUT 3, 4, 5, 6, 7
IN 8, 9, 10, 11
OUT 12, 13
IN 14
到目前为止我写的代码
enum Direction { IN, OUT }
class Tuple {
Direction direction;
int[] data;
public Tuple merge(Tuple t) {
return new Tuple(direction, concat(getData(), t.getData()));
}
}
private static int[] concat(int[] first, int[] second) {
int[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
List<Tuple> reduce = tupleStream.reduce(new ArrayList<>(), WDParser::add, WDParser::combine);
private static List<Tuple> combine(List<Tuple> list1, List<Tuple> list2) {
System.out.println("combine");
list1.addAll(list2);
return list1;
}
private static List<Tuple> add(List<Tuple> list, Tuple t) {
System.out.println("add");
if (list.size() == 0) {
list.add(t);
} else if (list.size() > 0) {
int lastIndex = list.size() - 1;
Tuple last = list.get(lastIndex);
if (last.getDirection() == t.getDirection())
list.set(lastIndex, last.merge(t));
else
list.add(t);
}
return list;
}
我相信有一个更好、更简单的替代方案来实现同样的目标。
我为 Java 流 api reduce/combine 找到的在线示例和博客仅使用 Integer::sum 函数。希望为更复杂的案例场景建立这个。
解决方案
我认为您的解决方案已经很不错了,尤其是与收集到共享的外部容器相比,使用归约可以轻松实现并行性。但它更容易使用collect
,而不是reduce
Holger 指出的那样。此外,累加器中的条件可以简化一点,您忘记合并组合器中的最后一个元素和第一个元素:
List<Tuple> reduce = tupleStream.collect(ArrayList::new, WDParser::add, WDParser::combine);
private static List<Tuple> combine(List<Tuple> list1, List<Tuple> list2)
{
if (!list2.isEmpty())
{
add(list1, list2.remove(0)); // merge lists in the middle if necessary
list1.addAll(list2); // add all the rest
}
return list1;
}
private static List<Tuple> add(List<Tuple> list, Tuple t)
{
int lastIndex = list.size() - 1;
if (list.isEmpty() || list.get(lastIndex).getDirection() != t.getDirection())
{
list.add(t);
}
else
{
list.set(lastIndex, list.get(lastIndex).merge(t));
}
return list;
}
而不是使用索引来访问你甚至可以使用的第一个/最后一个元素LinkedList
和方法add/removeFirst/Last()
。
推荐阅读
- c# - WCF - 从另一个 Web 应用程序(WCF 或 REST API)调用时出现 EndpointNotFoundException
- c - 如何解决c中的分段错误?
- firebase - Flutter 上的 Firebase 错误:无法解析配置“:firebase_core:debugCompileClasspath”的所有任务依赖项
- angular - 在移动断点之后在angular-gridster2中从左到右排序gridster项目
- c# - 收到错误消息:CS0029:无法隐式转换(ASP.NET Core MVC 和 C#)
- visual-studio-code - VSCode:在特定项目文件夹中创建文件的键盘快捷键?
- python - 更改拆分列名称并从表中捕获数据
- c# - 使用组策略将自定义 Windows 服务安装到所有域设备
- huawei-mobile-services - canvas组件绘制的图片无法在相册中显示
- c# - Main window in WPF application is not showing in screen share in skype or teams