I have a class called Info
public class Info {
private String account;
private String opportunity;
private Integer value;
private String desc;
}
I want to group a list of Info
, by two fields(account and then opportunity) and then sort it based on value. i.e.
List of info before grouping and sorting:
List<Info> infos = [(account = 1234, opportunity = abs, value = 4, desc= test),
(account = 1234, opportunity = abs, value = 5, desc = testing),
(account = 1234, opportunity = abss, value = 10, desc = vip),
(account = 123, opportunity = abss, value = 8, desc = vip),
(account = 12, opportunity = absddd, value = 4, desc = production),
(account = 12, opportunity = absooo, value = 2, desc = test)]
The result I expected after grouping and sorting,
Map<String, Map<String, List<Info>>> result = {
1234 = {
abss = [(account = 1234, opportunity = abss, value = 10, desc = vip)],
abs = [(account = 1234, opportunity = abs, value = 5, desc = testing),
(account = 1234, opportunity = abs, value = 4, desc = test)]
},
123 = {
abss = [(account = 123, opportunity = abss, value = 8, desc = vip)]
},
12 = {
absddd = [(account = 12, opportunity = absddd, value = 4, desc = production)],
absooo = [(account = 12, opportunity = absooo, value = 2, desc = test)]
}
}
o/p is sorted based on value(10->(5+4)->8->4->2)
I have tried so far = infos.stream().collect(Collectors.groupingBy(Info::getAccount, Collectors.groupingBy(r -> r.getOpportunity(), Collectors.toList())))
but its sorting randomly.
To sort base on the
value
ofInfo
,value
, such that grouping will execute in order.mapFactory
to preserve the insertion order .Following program demonstrates how to implement.