7

This is not my real code I have just simulated in order to understand what to do next.

I have class Person with properties age, height weight.
Now In my class Group
I create two four objects

Person programmer, student, clerk, tech;

I have HashMap rollCall

Map<Person, Integer> rollCall = new HashMap<Person, Integer>();

to add all these using Person and number of Persons as type Integer

rollCall.put(programmer, 1);
rollCall.put(clerk, 2);
rollCall.put(student, 1);
rollCall.put(tech, 3);

I have seen alot of people sorting HashMap using TreeMap on value I want to sort on a property of Person rather on value. I want to sort all these people on their age (i.e. programmer.getAge();). I am not sure if I will use comprator which works only on collection not map. . Please help ... .

Aahil
  • 71
  • 1
  • 1
  • 2

5 Answers5

7

You can get a Map<Person,Integer> which iterates by age increasing or decreasing order by using a custom comparator:

Map<Person, Integer> rollCall = new TreeMap<Person, Integer>(
  new Comparator<Person>() {
    @Override public int compare(Person p1, Person p2) {
      return p1.getAge() - p2.getAge(); // Acending.
      // or  p2.getAge() - p1.getAge(); // Descending.
    }
  }
);

When you add Persons to the collection they will be inserted in order by age.

maerics
  • 151,642
  • 46
  • 269
  • 291
1

First of all, TreeMap sorts on keys, not values. So that's already working in your favor. Any object you use as a key in a TreeMap must implement Comparable, or you must provide a Comparator as a constructor argument. All you need to do is have your compareTo() method (from Comparable) or compare() method (from Comparator) compare based on your getAge() property.

The TreeMap constructor that takes a Comparator is described here. The Comparator will be used to sort the keys in the map.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • I am not willing to mess up with my Person class. in that case I must create a new Comprator class and use Compare(Object o1, Object o2) method. but the problem here is that Comprator works only with collections not Maps ?? Is there a way to use comprator for TreeMap ? any example ? – Aahil Jun 07 '11 at 02:32
  • 1
    I added a link to the constructor I mentioned to my answer above. This constructor takes a `Comparator` as an argument, and uses it to compare the keys. – Ernest Friedman-Hill Jun 07 '11 at 02:46
1

You need to be able to compare your Person objects. If there is a canonical way to compare them, let them implement Comparable<Person> (i.e. give them a compareTo(Person) method.

If this is done, you can use the persons as keys for a SortedMap (like TreeMap).

If there are multiple ways two persons could be compared, implement a Comparator<Person> as a separate object.

Then give this comparator to the SortedMap on construction.

This will not sort your HashMap (a HashMap has always a seemingly random order), but give you another sorted datastructure instead.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
0
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class PersonSort {

    private MySort sort = new MySort();
    private Map<Person, String> map = new HashMap<Person, String> ();
    private Map<Person, String> treeMap = new TreeMap<Person, String>(sort);

    Person e1 = new Person(500, "Saurabh");
    Person e2 = new Person(400, "Kishan");
    Person e3 = new Person(900, "Ashwini");

    public void myMap() {

        map.put(e3, "Ash");
        map.put(e2, "Krish");
        map.put(e1, "Sau");

        Iterator it = map.keySet().iterator();
        System.out.println("UnSorted Map");
        while(it.hasNext()) {
            System.out.println(map.get(it.next()));
        }

        treeMap.putAll(map);
        System.out.println("SortedMap");
        Iterator it1 = treeMap.keySet().iterator();
        while(it1.hasNext()) {
            System.out.println(treeMap.get(it1.next()));
        }
    }

    public static void main(String[] args) {
        PersonSort es = new PersonSort();
        es.myMap();
        }
}

class Person {
    Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
    private int id;
    private String name;
    //Getters and Setters
}

class MySort implements Comparator<Object> {
    public int compare(Object o1, Object o2) {
        return ((Person) o1).getId() - ((Person)o2).getId();
    }
}
Saurabh Kachhia
  • 300
  • 3
  • 12
-1
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/*
 * Sort HashMap that contains Student object
 */

public class SortHashMap implements Comparator<Student>
{
    public static void main(String[] args)
    {
        Map map = new HashMap();
        map.put("s1", new Student(5,"utpal"));
        map.put("s2", new Student(4,"ramesh"));
        map.put("s3", new Student(10,"tushar"));
        map.put("s4", new Student(2,"anindya"));
        Collection<Student> students = map.values();
        List list = new ArrayList(students);
        Collections.sort(list,new SortHashMap());

        for (Iterator it = list.iterator(); it.hasNext();) 
        {         
            Student stdn = (Student)it.next();             
            System.out.println("Student id : "+stdn.id);
            System.out.println("Student Name : "+stdn.name);            
        } 
    }
    @Override
    public int compare(Student s1, Student s2) 
    {
        return s1.name.compareTo(s2.name);
    }
}

class Student 
{    
    int id;
    String name;
    Student(int id,String name)
    {
        this.id = id;
        this.name = name;
    }    
}
Jonathan
  • 3,016
  • 9
  • 43
  • 74