可以将java stream groupingby返回到此的数组变量吗?

7kjnsjlb  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(194)

q、 1)您好,java stream的groupingby可以使自己的数组可变吗?
这是实体

public class Test {
   private int id;
   private int itemId;
   private int[] itemIds;
   private boolean filter;
}

这是测试列表样本

{
   test(id=1, itemId=1)
   test(id=1, itemId=2)
   test(id=1, itemId=3)
   test(id=2, itemId=5)
   test(id=2, itemId=11)
}

例如,我希望使用test.id分组

{
   test(id=1, itemIds=[1,2,3])
   test(id=2, itemIds=[5,11])
}

我该怎么办?

tests.stream().collect(Collectors.groupingBy(Test::getId), ?, ?);

q、 2)如何合并以下两个流代码?

tests.stream().filter(Test::isFilter).anyMatch(t -> {throw new Exception;});
tests.stream().collect(Collectors.groupingBy(Test::getId, ?, ?); // Q1 result

关于这个。。?

tests.stream().filter(Test::isFilter).anyMatch(t -> {throw new Exception;}).collect(Collectors.groupingBy(Test::getId, ?, ?);

q3)在q1以上,q2的流代码比java“for”语法的性能更好?
提前谢谢。:)

9cbw7uwe

9cbw7uwe1#

用于假设构造函数 Test(int id, int itemId, int[] itemIds) 以及诸如 id() , itemId()itemIds() 您可以通过以下方式取消数据平台:

List<Test> unflattenedTests = tests.stream()
   .collect(Collectors.groupingBy(Test::id))
   .entrySet().stream().map(e -> new Test(
       e.getKey().intValue(),
       0,
       e.getValue().stream().mapToInt(Test::itemId).toArray()
    ))
    .collect(Collectors.toList());

至于合并你的过滤器&在一个语句中抛出逻辑,我真的想不出任何其他方法 peek 例如:

List<Test> unflattenedTests = tests.stream()
   .peek(t -> { if (t.isFilter()) throw new RuntimeException(); })
   .collect(...
oxosxuxt

oxosxuxt2#

@谢谢你的回答!
感谢您的回答,这是我的解决方案

tests.stream()
    .peek(t -> {if (Test::isFilter) throw new Exception();})
    .collect(Collectors.groupingBy(Test::getId, Collectors.mapping(Test::getItemId, Collectors.toSet())))
    .forEach((id, itemIdSet) -> {
        if (!somBusiness(id, itemIdSet)) {
            throw new Exception();
        }
    };

你怎么看,我的解决方案。我担心性能不好。
无论如何,我的知识已经升级了!非常感谢。:)

相关问题