Java Collection How to - Sort objects in HashMap on their properties rather than values








Question

We would like to know how to sort objects in HashMap on their properties rather than values.

Answer

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
//  w ww  . j a va  2 s .co m
public class Main {
  public static void main(String[] args) {
    Map<String, Student> map = new HashMap<>();
    map.put("s1", new Student(5, "A"));
    map.put("s2", new Student(4, "B"));
    map.put("s3", new Student(10, "C"));
    map.put("s4", new Student(2, "D"));
    Collection<Student> students = map.values();
    List<Student> list = new ArrayList<>(students);
    Collections.sort(list, new MyComparator());

    for (Iterator<Student> it = list.iterator(); it.hasNext();) {
      Student stdn = (Student) it.next();
      System.out.println("Student id : " + stdn.id);
      System.out.println("Student Name : " + stdn.name);
    }
  }
}

class MyComparator implements Comparator<Student> {

  @Override
  public int compare(Student s1, Student s2) {
    return s1.name.compareTo(s2.name);
  }
}

class Student {
  int id;
  String name;

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

The code above generates the following result.