2

I am having a HashMap with Strings as key and Objects as value. How can i sort HashMap by FirstName field inside Objects. Here is the actual HashMap representation HashMap<String, AttendanceData> attendanceDataMap=new HashMap<String, AttendanceData>();

Key of the HashMap will be id of AttendanceData Object

AttendanceData Class look like

public class AttendanceData{

private TakenBy takenBy;

private String id;

private String user_name;

private String first_name;

private String description;

private String last_name;

public AttendanceData(String id, String firstName, String lastName, String takenBy, String description, String userName)
{
    this.id=id;
    this.first_name=firstName;
    this.last_name=lastName;
    this.takenBy=takenBy;
    this.description=description;
    this.user_name=userName;
}

2 Answers2

1

I think a Comparator might be helpful, pasting an example below, please note this is not a concrete answer, you must modify it according to your needs:

public class HMapSortingByvalues {
  public static void main(String[] args) {
      HashMap<Integer, String> hmap = new HashMap<Integer, String>();
      hmap.put(5, "A");
      hmap.put(11, "C");
      hmap.put(4, "Z");
      hmap.put(77, "Y");
      hmap.put(9, "P");
      hmap.put(66, "Q");
      hmap.put(0, "R");
      System.out.println("Before Sorting:");
      Set set = hmap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
           Map.Entry me = (Map.Entry)iterator.next();
           System.out.print(me.getKey() + ": ");
           System.out.println(me.getValue());
      }
      Map<Integer, String> map = sortByValues(hmap); 
      System.out.println("After Sorting:");
      Set set2 = map.entrySet();
      Iterator iterator2 = set2.iterator();
      while(iterator2.hasNext()) {
           Map.Entry me2 = (Map.Entry)iterator2.next();
           System.out.print(me2.getKey() + ": ");
           System.out.println(me2.getValue());
      }
  }

  private static HashMap sortByValues(HashMap map) { 
       List list = new LinkedList(map.entrySet());
       // Defined Custom Comparator here
       Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
               return ((Comparable) ((Map.Entry) (o1)).getValue())
                  .compareTo(((Map.Entry) (o2)).getValue());
            }
       });

       // Here I am copying the sorted list in HashMap
       // using LinkedHashMap to preserve the insertion order
       HashMap sortedHashMap = new LinkedHashMap();
       for (Iterator it = list.iterator(); it.hasNext();) {
              Map.Entry entry = (Map.Entry) it.next();
              sortedHashMap.put(entry.getKey(), entry.getValue());
       } 
       return sortedHashMap;
  }
}
Skynet
  • 7,820
  • 5
  • 44
  • 80
0

HashMap does not support sorting. But of course, you can sort values. Implement Comparable eg:

List list = new ArrayList(Map.entrySet());
Collections.sort(list, new Comparator() {
  @Override
  public int compare(Entry e1, Entry e2) {
    return e1.getValue().compareTo(e2.getValue());
  }
});

In addition, you can use SortedMap (TreeMap eg). But it only supports sorting by keys. Although you can try to use this comparator:

class ValueComparator implements Comparator {

  Map base;
  public ValueComparator(Map base) {
      this.base = base;
  }

  public int compare(Object a, Object b) {

    if((Double)base.get(a) < (Double)base.get(b)) {
      return 1;
    } else if((Double)base.get(a) == (Double)base.get(b)) {
      return 0;
    } else {
      return -1;
    }
  }
}
user2413972
  • 1,355
  • 2
  • 9
  • 25