Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - sorting a hashmap with date inside value object [duplicate]

Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?

Suppose am having a map like

Map<String, Student> studDetails = new HashMap<String, Student>();

And the map contains entries like

studDetails.put("1",student1);
studDetails.put("2",student2);
studDetails.put("3",student3);
studDetails.put("4",student4);

Student entity is Something like

Class Student{
           private String studName;
           private List<Group> groups;
}

Group entity will be like

Class Group{
             private String groupName;
             private Date creationDate;
}

OK, so what I need is when am displaying student details, it will be in the order of group creation date. So if student is mapped to more than one group, we can take the creationDate of first group.

How can I given the soring on my HashMap studDetails using this scenario.?

Can anyone help..please..

like image 886
Tijo Avatar asked Dec 07 '25 13:12

Tijo


2 Answers

HashMap is not sorted you should use a SortedMap implementation instead for example TreeMap.

Then you could create your own Comparator<String> which will sort by the groups attribute of the actual Student instance but you'll need the actual map for it because TreeMap sorts by the keys, so this is a possible but not nice solution.

So with TreeMap:

public class StudentGroupComparator implements Comparator<String> {
  private Map<String, Student> sourceMap;

  public StudentGroupComparator(Map<String, Student> sourceMap) {
    this.sourceMap = sourceMap;
  }

  @Override
  public int compare(String key1, String key2) {
    // TODO: null checks
    Student student1 = sourceMap.get(key1);
    Student student2 = sourceMap.get(key2);

    Date o1CreationDate = student1.groups.get().creationDate;
    Date o2CreationDate = student2.groups.get().creationDate;
    return o1CreationDate.compareTo(o2.creationDate);
  }
}


SortedMap<String, Student> sortedMap = new TreeMap<String, Student>(new StudentGroupComparator(sourceMap));
sortedMap.putAll(sourceMap);
like image 92
KARASZI István Avatar answered Dec 10 '25 02:12

KARASZI István


How can I given the soring on my HashMap studDetails using this scenario?

You can't, because HashMap is fundamentally unordered (or at least, the ordering is unstable and unhelpful).

Even for sorted maps like TreeMap, the sort order is based on the key, not the value.

like image 27
Jon Skeet Avatar answered Dec 10 '25 04:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!