java 8 group by_将对象中的列表按多个属性分组:Java 8(Group a list inside an object by multiple attributes : Java 8)...

How do I group a list inside an object by two of the object attributes?

I’m using Drools 7.9.0 and Java 8. I have a Result class that is used as return to each matched Drools rule.

import lombok.Data;

import lombok.NoArgsConstructor;

import java.io.Serializable;

import java.util.ArrayList;

import java.util.List;

@Data

@NoArgsConstructor

public class Result implements Serializable {

private Integer id;

private String name;

private List occurrences = new ArrayList<>();

public void addOccurrence(Occurrences occurrence) {

this.occurrences.add(occurrence);

}

}

After Drools execution, I end up with a List. Converted to JSON it looks like this.

CURRENT OUTCOME:

[

{

name: "Whatever"

id: 0001,

occurrences: [{

(...)

}]

},

{

name: "Whatever"

id: 0001,

occurrences: [{

(...)

}]

},

{

name: "Whatever"

id: 0002,

occurrences: [{

(...)

}]

},

{

name: "Other thing"

id: 0002,

occurrences: [{

(...)

}]

}

]

I need to group up my list of Results so the ocurrences are grouped by id and name, like this.

EXPECTED OUTCOME:

[

{

name: "Whatever"

id: 0001,

occurrences: [{

(...)

}, {

(...)

}]

},

{

name: "Whatever"

id: 0002,

occurrences: [{

(...)

}]

},

{

name: "Other thing"

id: 0002,

occurrences: [{

(...)

}]

}

]

What would be the best way to implement this? I have two options:

Change Drools rules so my List is already structured the way I need. Maybe create a class with a addResult method that checks the list for id and name and add the occurrence to the right entry. But this is not ideal, because it will increase complexity inside the rules.

Post-process my List so it groups the occurrences by id and name. But I have no idea how to do this in an optimized and simple way.

What’s the best way to do the 2nd option?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值