0
{
    "response": [
        {
            "messages": [
                {
                    "parameters": {
                        "PRECEDENCE": "3",
                        "ENTITY_CLASS": "ACCOUNT"
                    }
                },
                {
                    "parameters": {
                        "PRECEDENCE": "16",
                        "ENTITY_CLASS": "PRODUCT"
                    }
                },
                {
                    "parameters": {
                        "PRECEDENCE": "1",
                        "ENTITY_CLASS": "ACCOUNT"
                    }
                }
            ]
        }
    ]
}

I want the output should be ordered based value in ascending order

{
    "response": [
        {
            "messages": [
                {
                    "parameters": {
                        "PRECEDENCE": "1",
                        "ENTITY_CLASS": "ACCOUNT"
                    }
                },
                {
                    "parameters": {
                        "PRECEDENCE": "3",
                        "ENTITY_CLASS": "PRODUCT"
                    }
                },
                {
                    "parameters": {
                        "PRECEDENCE": "16",
                        "ENTITY_CLASS": "ACCOUNT"
                    }
                }
            ]
        }
    ]
}

Current structure I have

Response 
        Set<essage> message
                        Map<String, String> parameters = new HashMap<>();
                        

I was trying by manual compare. is there a way I can iterate and sort the map values.

How can I optimize efficiently?

Naman
  • 27,789
  • 26
  • 218
  • 353
user3123934
  • 1,001
  • 3
  • 12
  • 19
  • there is an example here might be useful. https://www.geeksforgeeks.org/sorting-hashmap-according-key-value-java/ – AntiqTech Sep 01 '21 at 16:19
  • Also, If you want to sort by interger value of the keys, there is a comparator example : https://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java – AntiqTech Sep 01 '21 at 16:21

1 Answers1

0

First of all, I have to change the message type from a Set to List if the order is important for you.

Next, you have to implement Comparator for your Message to simplify the way of sorting, the compare method may look like next:

    public int compareTo(Message msg1, Message msg2){
       return msg1.parameters.get("PRECEDENCE")
                  .compareTo(msg2.parameters.get("PRECEDENCE")) 
    }

Don't forget to add different null checks.

Then you can simply call response.messages.sort(new YourMessageComparator()) to get sorted messages by precedence.

Kirill Liubun
  • 1,965
  • 1
  • 17
  • 35