以下是场景:
我有一个Segment对象列表:我需要按照组进行分组的列表段。
**细分数据**
[CODE]: 9X-594 (D/ET) - [SET]: 1
[CODE]: 9X-600 (D/ET) - [SET]: 2
[CODE]: 9X-602 (D/ET) - [SET]: 3
[CODE]: 9X-596 (D/ET) - [SET]: 4
[CODE]: 9X-970 (S/ET) - [SET]: 5
[CODE]: 9X-579 (E/ET)
[CODE]: 9X-974 (S/ET) - [SET]: 6
[CODE]: 9X-589 (E/ET)
[CODE]: 9X-599 (E/ET)
[CODE]: 9X-964 (S/ET) - [SET]: 7
[CODE]: 9X-581 (E/ET)
我需要将这些数据分组为以下格式:
List<CodeSample> samples = new ArrayList<CodeSample>();
其中CodeSample是包含Segment列表的类。
public class CodeSample {
private int set;
private List<Segment> segments;
//getters/setters here
...
}
我需要按集合对细分进行分组,例如:
samples = [
{ set: 1, [{code: "9x-594 (D/ET)"}]},
{ set: 2, [{code: "9x-600 (D/ET)"}]},
{ set: 3, [{code: "9x-602 (D/ET)"}]},
{ set: 4, [{code: "9x-596 (D/ET)"}]},
{ set: 5, [{code: "9x-970 (D/ET)"}, {code: "9x-579 (D/ET)"}]},
{ set: 6, [{code: "9x-974 (D/ET)"}, {code: "9x-589 (D/ET)"}, {code: "9x-599 (D/ET)"}]},
{ set: 7, [{code: "9x-964 (D/ET)"}, {code: "9x-581 (D/ET)"}]}
]
我需要创建一个包含段列表(已分组)的样本列表。
此方案的最佳方法是什么?
答案 0 :(得分:2)
List<CodeSample> result =
segments.stream()
.collect(Collectors.groupingBy(Segment::getSet))
.entrySet()
.stream()
.map(entry -> new CodeSample(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());