javasortingmaps

Sorting Map using Comparator by Map value


I'm not sure if I've seen any answer that suits my situation, despite on a bunch of answers for situations which are look alike. Anyway I'm a JAVA noob, so please be indulgent.

Here's the deal:

  1. I have some class which is presents, let's say, a Person with name which is a String.

  2. Also I have a Comparator (MyComparator) that implements a Comparator interface for Persons. The Comparator's constructor assumes that all comparable objects (Persons) will be kept in a Map<Person, Integer>. In Comparator I have an int compare (Person p1, Person p2) method which is written by the following way:

    public int compare (Person personOne, Person personTwo) {
       if (personsMap.get(personOne)>personsMap.get(personTwo)) {
          return 1;
       } else if (personsMap.get(personOne)<personsMap.get(personTwo)) {
          return -1;
       } else {
         return 0;
       }
    

When I run something like this:

public static void main (String[] args) {
    Person p1 = new Person ("Willy");
    Person p2 = new Person ("Billy");
    Person p3 = new Person ("Dilly");

    Map<Person, Integer> t = new HashMap<Person, Integer>();
    t.put(p1,12);
    t.put(p2,2);
    t.put(p3,100);

    List<Person> pl = new Arrays.asList(p1,p2,p3);
        Collections.sort(pl, new MyComparator(t));
}

I get NPE in MyComparator at the following row:

 if (personsMap.get(p1)>personsMap.get(p2)) 

Please, give me a clue, how to fix this. Thanks in advance.


Solution

  • I guess that you are not initializing the map in your Comparator's constructor..

    public MyComparator(Map<Person, Integer> t) {
            this.personsMap = t;
    }
    

    It's the most probable case in which you can have NPE. But you haven't inserted all the comparator class so it's just a guess ..