0

I want to sort a TreeMap by ascending order wrt "Student.name". I don't want to create a new ArrayList. Is there any way to do this?

Map studentMap = new TreeMap();
studentMap.put(id, student); //id is double

public class Student{
String name;
int number;
....

}
hellzone
  • 5,393
  • 25
  • 82
  • 148

4 Answers4

2

You can do this in two ways:

  1. Since you can't pass a value-based comparator to TreeMap, you can do this:
    TreeMap sort by value

  2. Making Student implement Comparable interface

    public class Student implements Comparable<Student> {
        @Override
        public int compareTo(Student o) {
            return this.getName().compareTo(o.getName());
        }
    }
    

In first case, you need to call the mentioned method on your collection. In the second one, just add students to your map.

Community
  • 1
  • 1
ioreskovic
  • 5,531
  • 5
  • 39
  • 70
1

You can use a custom comparator for that while creating the TreeMap.

Map studentMap = new TreeMap(new Comparator<Student>() {
    @Override
    public int compare(Student o1, Student o2) {
        // Your logic to sort it based on Student name goes here
        return 0;
    }
});
Rahul
  • 44,383
  • 11
  • 84
  • 103
  • The TreeMap is a structure which is kept sorted as you insert elements into it. All you need to do is what R.J wrote, just provide the right comparator so that Students are sorted as they are inserted into the map. – peter.petrov Nov 27 '13 at 09:45
  • @peter.petrov if(o1.getName() == null || o2.getName() == null){ return -1; } is this enough for null values? – hellzone Nov 27 '13 at 09:50
  • You can treat null either as bigger than any other non-null value or as smaller than any other non-null value. It's up to you. So no, this is not enough (I think even it's not logically correct). You need to look at all 4 cases: 1) both null /return 0/; 2) first is null /return +1 or -1/; 3) second is null /return -1 or +1 respectively/; 4) both are not null /compare them with equals /. – peter.petrov Nov 27 '13 at 10:00
1

if you are using TreeMap then the record will be already sorted .You need to implement the Comparable interface in Student class and have to override the compareTo method

Student implements Comparable {

  // override compareTo wrt name
  @Override
  public int compareTo(Student otherStudent) {
     return name.compareTo(otherStudent.name);
  }
}
Deepak
  • 2,287
  • 1
  • 23
  • 30
0

TreeMap is sorting its entries according to keys, not values. You cannot provide a Comparator<Student> since you have Double keys.

If you really need a map from Double to Student you cannot sort it in the way you want. If not consider using a TreeSet<Student> with a Comparator<Student> or Comparable<Student>.

Dmitry Tikhonov
  • 301
  • 1
  • 8