Stream grouping by sum of determinate objects


Stream grouping by sum of determinate objects



I have a Request class like this :


public class Request
{
String name,destName;
int nSeats;
//Example : requestOne,Paris,3
...
}



I want to group the request in a Map |Integer,List of String| where the keys are the sum of the request with the same destName and the values are the destinations' names.



Here is my code:


public TreeMap<Integer, List<String>> destinationsPerNSeats() {
return requests.
stream().
collect(Collectors.groupingBy(Request::getnSeats, TreeMap::new,
Collectors.mapping(Request::getDestName, Collectors.toList()))).
}



Input :


TreeMap<Integer, List<String>> map = mgr.destinationsPerNSeats();
print(map);



Output : {4=[Paris], 3=[London, Berlin, Berlin], 2=[Paris]}



Output expected : {6=[Berlin, Paris], 3=[London]}



How can I solve this? Thanks!





What did you use as Input?
– Glains
8 mins ago





what is the input?
– Ravindra Ranwala
8 mins ago




1 Answer
1



I think you need two Stream pipelines. The first will group the destinations and count the total number of seat in each destination, and the second will group the destinations by number of seats:


Stream


public TreeMap<Integer, List<String>> destinationsPerNSeats() {
return
requests.stream()
.collect(Collectors.groupingBy(Request::getDestName,
Collectors.summingInt(Request::getnSeats)))
.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
TreeMap::new,
Collectors.mapping(Map.Entry::getKey,Collectors.toList())));
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Export result set on Dbeaver to CSV

Opening a url is failing in Swift