-1

I have a model class

class UserMeter{
int id;
String meterNo; // meter number in a-z,0-9
String readingValue; //in a-z,0-9
String priority; //{low,medium,high,danger,overflow}

//getter setter
}

When i call an API i get list of UserMeter. but the result are random. i want to show the result by sorting priority wise. i need for high performance logic/algorithm to achieve this.

update: What i tried is

Collections.sort(userMeterList, new Comparator<UserMeter>() {
                    @Override
                    public int compare(UserMeter m1, UserMeter m2) {
                        String p1 = m1.getPriority();
                        String p2 = m2.getPriority();
                        if (p1 == null) return 1;
                        if (p2 == null) return -1;
                        if (p1.equals(p2)) return 0;
                        return m1.getPriority().compareTo(m2.getPriority());
                    }
                });

The output does not match desire result. i.e. (danger,high,medium,low,overflow) I want to show the priority from low to danger.(low,medium,high,danger,overflow)

Deepak Maurya
  • 67
  • 1
  • 9
  • 3
    Does this answer your question? [Why should a Java class implement comparable?](https://stackoverflow.com/questions/3718383/why-should-a-java-class-implement-comparable) – QBrute Feb 26 '20 at 17:44

1 Answers1

1

First declare a map or any other data structure to give priorities a int value, thus it would be easier to code. For example:

Map<String, Integer> mp = new HashMap<>();
    mp.put("low", 1);
    mp.put("medium", 2);
    mp.put("high", 3);
    mp.put("danger", 4);
    mp.put("overflow", 5);

Then update the compare function like below. This should work. Let me know if don't understand any part. Happy Coding!

Collections.sort(userMeters, new Comparator<UserMeter>() {
                @Override
                public int compare(UserMeter m1, UserMeter m2) {
                    if (mp.get(m1.getPriority()) == mp.get(m2.getPriority())) return 0;
                    if (mp.get(m1.getPriority()) > mp.get(m2.getPriority())) return 1;
                    return -1;
                }
            });
Md Golam Rahman Tushar
  • 2,175
  • 1
  • 14
  • 29
  • I was thinking to do same but in case if any priority added by back-end API. In that case i have to add that manual code priority code(Hard code). Even enum need to compile the whole source code again. however your solution is perfect for current situation.thanks md golam. – Deepak Maurya Feb 27 '20 at 06:49