Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Grouping and sorting together in JAVA 8 [duplicate]

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.

like image 698
Abhishek Galoda Avatar asked Jan 30 '23 10:01

Abhishek Galoda


2 Answers

This solution worked for me

        .sorted(Comparator.comparing(DXARoom::getStayAverageRate))
        .collect(Collectors.groupingBy(DXARoom::getRateInfoLabel, LinkedHashMap::new, Collectors.toList()));

Basically first,

  • We need to sort the whole list
  • Group list in a new LinkedHashMap as it preserves the insertion order, which is the key

Thanks @Holger

like image 143
Abhishek Galoda Avatar answered Feb 02 '23 12:02

Abhishek Galoda


Seems like you are looking for this:

Collectors.groupingBy(
        DXARoom::getRoomInfoLabel,
        LinkedHashMap::new,
        Collectors.toList());
like image 43
Eugene Avatar answered Feb 02 '23 12:02

Eugene