java根据变量收集流和分组

时间:2018-01-25 16:33:27

标签: java grouping java-stream collect

我获得了这两个班级"交易"它具有Trader trader,int year,int value,long seq和" Trader"的属性。它具有属性String name,String city。

我需要将此流分组并仅在seq = seq + 1

时加总
    Trader raoul = new Trader("Raoul", "Cambridge");
    Trader mario = new Trader("Mario","Milan");
    Trader alan = new Trader("Alan","Cambridge");
    Trader brian = new Trader("Brian","Cambridge");

    List<Transaction> transactions = Arrays.asList(
        new Transaction(brian, 2012, 300, 1), 
        new Transaction(raoul, 2012, 1000, 2),
        new Transaction(raoul, 2012, 400, 13),
        new Transaction(mario, 2012, 710, 14),  
        new Transaction(mario, 2012, 700, 94),
        new Transaction(alan, 2012, 950, 95)
    );  

我怎样才能做到这一点:

{Trader:Brian in Cambridge, year: 2012, value:1300, seq:1}, {Trader:Raoul in Cambridge, year: 2012, value:1110, seq:13}, {Trader:Mario in Milan, year: 2012, value:1650, seq:94}

请帮助!

1 个答案:

答案 0 :(得分:0)

示例解决方案:

Stream.concat(
    transactions.stream()
    .collect(Collectors.groupingBy(transaction -> transaction.seq / 2 ))
    .entrySet().stream(),

    transactions.stream()
    .collect(Collectors.groupingBy(transaction -> (transaction.seq + 1) / 2))
    .entrySet().stream()

    )
    .filter(elem -> elem.getValue().size() == 2)
    .map(entry -> entry.getValue().stream().reduce((left, right) -> new Transaction(left.trader, left.year, left.value + right.value, Long.min(left.seq, right.seq))).get())
    .collect(Collectors.toList())

以上代码:

  1. 根据事件的seq除以2对事务进行分组(因为在您的示例中,一对事务的序列可能以偶数和奇数开始,我们需要执行两次,一旦将分割结果四舍五入,一旦下降)
  2. 过滤掉不匹配的值(与上述两张地图中的连续交易不匹配的值)
  3. 将结果连接到单个流中,丢弃地图密钥
  4. 将事务对映射到表示原始事务的聚合状态的单个事务
  5. 请注意,如果事务对的序列始终以奇数

    开始,则可以进一步简化上述内容