0

I have the following ArrayList hashmap:

 [{username=p, diff=0.0}, {username=e , diff=314.0}, {username=e ,diff=90.0}, {username=p, diff=0.0}, {username=e, diff=94.0}, {username=z, diff=92.0} , {username=z, diff=102.0}  ]

Implementing code below i get the whole list sorted by "diff" key:

Collections.sort(final_itinList,
                            new Comparator<HashMap<String, String>>() {

                                @Override
                                public int compare(HashMap<String, String> lhs,
                                        HashMap<String, String> rhs) {                                  

                                    return Double.compare(
                                            Double.parseDouble(lhs.get("diff")),
                                            Double.parseDouble(rhs.get("diff")));

                                }
                            });

Now i have difficulties to sort the list by "diff" key only for these objects that have username different as "p". So I want for objects that have "p" username to stay at their positions and sort the others,like...

[{username=p, diff=0.0}, {username=e ,diff=90.0}, {username=e , diff=314.0},  {username=p, diff=0.0}, {username=z, diff=92.0} , {username=e, diff=94.0}, {username=z, diff=102.0}  ]

Any quick solution; Thanks in advance

1 Answer 1

1

If I understand well your problem, the quick solution will be to do like follows:

Collections.sort(final_itinList,
                        new Comparator<HashMap<String, String>>() {

                            @Override
                            public int compare(HashMap<String, String> lhs,
                                    HashMap<String, String> rhs) {                                  

                                    if( (lhs.get("username").compareTo("p")) == 0){
                                      return -1;
                                    }
                                return Double.compare(
                                        Double.parseDouble(lhs.get("diff")),
                                        Double.parseDouble(rhs.get("diff")));

                            }
                        });

This will check the username and if it is "p" then its value will be returned and its position will be the same as before!

Sign up to request clarification or add additional context in comments.

2 Comments

I get "Type mismatch: cannot convert from String to int" at line " return (lhs.get("diff"));"
I have edited my answer! Hope this will work. Otherwise you have to return positive value instead ! If you want to sort by descending order you have to return 1 otherwise return negative value!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.