我获得了这两个班级"交易"它具有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}
请帮助!
答案 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())
以上代码:
seq
除以2对事务进行分组(因为在您的示例中,一对事务的序列可能以偶数和奇数开始,我们需要执行两次,一旦将分割结果四舍五入,一旦下降)请注意,如果事务对的序列始终以奇数
开始,则可以进一步简化上述内容