Reputation: 5236
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;
....
}
Upvotes: 0
Views: 119
Reputation: 5699
You can do this in two ways:
Since you can't pass a value-based comparator to TreeMap, you can do this:
TreeMap sort by value
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.
Upvotes: 2
Reputation: 301
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>
.
Upvotes: 0
Reputation: 2895
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);
}
}
Upvotes: 1
Reputation: 45060
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;
}
});
Upvotes: 1