【问题标题】:can return java stream groupingby to this's array variable?可以将java流分组返回到这个数组变量吗?
【发布时间】:2021-09-19 10:56:48
【问题描述】:

Q.1) hi,java流的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' 语法性能更好?

提前谢谢你。 :)

【问题讨论】:

  • 对于第一季度,你可以简单地做tests.stream().collect(Collectors.groupingBy(Test::getId));

标签: java java-stream collectors groupingby


【解决方案1】:

对于假设像Test(int id, int itemId, int[] itemIds) 这样的构造函数和像id()itemId()itemIds() 这样的流式getter 进行分组,您可以通过这种方式展开数据:

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(...

【讨论】:

    【解决方案2】:

    @plalx感谢您的回答!

    感谢回答,这是我的解决方案

    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();
            }
        };
    

    你怎么看,我的解决方案。 我担心性能低下。

    反正我的知识升级了! 多谢。 :)

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多