I am trying to sort a list and then group the elements. Problem is that when I group the elements sorting order is going for a toss. Below is my piece of code
listOfRooms.stream().sorted(Comparator.comparing(DXARoom::getStayAverageRate))
.collect(Collectors.groupingBy(DXARoom::getRoomInfoLabel));
This is how my output is coming for the above code
{
"Presidential suite": [
{
"roomInfoLabel": "Presidential suite",
"stayAverageRate": "1696.0",
},
{
"roomInfoLabel": "Presidential suite",
"stayAverageRate": "1729.0",
},
"Premier king room": [
{
"roomInfoLabel": "Premier king room",
"stayAverageRate": "370.0",
},
{
"roomInfoLabel": "Premier king room",
"stayAverageRate": "377.0",
},
}
Basically, my requirement is to show cheapest room type first. So the output should be grouped by Premier king room first as it has the cheapest Room of 370£.
EXPECTED OUTPUT ->
{
"Premier king room": [
{
"roomInfoLabel": "Premier king room",
"stayAverageRate": "370.0",
},
{
"roomInfoLabel": "Premier king room",
"stayAverageRate": "377.0",
},
"Presidential suite": [
{
"roomInfoLabel": "Presidential suite",
"stayAverageRate": "1696.0",
},
{
"roomInfoLabel": "Presidential suite",
"stayAverageRate": "1729.0",
}
}
Can you please suggest me any alternative method or whats wrong with above implementation, any new ideas are welcome.
This solution worked for me
.sorted(Comparator.comparing(DXARoom::getStayAverageRate))
.collect(Collectors.groupingBy(DXARoom::getRateInfoLabel, LinkedHashMap::new, Collectors.toList()));
Basically first,
Thanks @Holger
Seems like you are looking for this:
Collectors.groupingBy(
DXARoom::getRoomInfoLabel,
LinkedHashMap::new,
Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With