0

I have a HashMap with objects of a class (obj1, obj2, obj3) as keys and java.util.Date (date1, date2, date3)as values. The HashMap is already sorted based on the values, i.e., based on the date objects. The key objects are having property called name.

obj1.name = "name1", obj2.name = "name2" etc.

Now, When the values of HashMap are same, i.e., when there are same dates as values, I need to check the name of the key object (obj.name) and sort the HashMap based on name propery of key object. Note that I need to sort based on the name property of key object only when the HasHMap has same date as values.

For example, I have the below HashMap

[obj1=Tue Jul 01 00:00:00 IST 2014,obj2=Thu Jul 03 00:00:00 IST 2014,obj3=Thu Jul 03 00:00:00 IST 2014,obj4=Sun Jul 06 00:00:00 IST 2014]

And the name property of each key object is

obj1.name = "B";

obj2.name = "D";

obj3.name = "A";

obj4.name = "C";

Then finally I need to sort the HashMap to get the keySet in the order [obj1,obj3,obj2,obj4], since keys obj2 and obj3 have same date values and hence to be sorted based on name property of key objects.

Raheeb M
  • 13
  • 7
  • Its very similar to this: http://stackoverflow.com/a/1283722/1651233. You just need to add key.name inside `compare`. – BobTheBuilder Nov 13 '14 at 06:56
  • I see multiple answers there. Could you please clarify which answer you are referring to? – Raheeb M Nov 13 '14 at 07:26
  • 2
    It's generally best to avoid sorting a Mapping structure. The reason being is a map is supposed to be a lookup table. When finding a value, it takes O(1) time to look it up. There is no need to sort it. I would consider going with a different data structure if possible. – DanSchneiderNA Nov 13 '14 at 07:33

1 Answers1

0

You can use the Java Comparable interface for this, make your class implement this interface and then implement its compareTo() method based on comparing the names.

public class Emp implements Comparable<Emp>{
    int id;
    String name;

    Emp(int id, String name){
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Emp o) {
        return this.name.compareTo(o.name);
    }
}

I would recommend instead of using a HashMap use a TreeMap(or, convert it into TreeMap) which will insert the records based on the natural order of key, in this case, based on the comparison done.

Map<Emp, EmpData> map = new TreeMap<>();

map.put(e1,data1);
map.put(e2,data2);
map.put(e3,data3);
map.put(e4,data4);

map.forEach((Emp, Empdata) -> System.out.println("Key : "+Emp.toString()+", Value: "+Empdata.toString()));
abhishek narayan
  • 109
  • 1
  • 1
  • 10