0
public class Employee {

    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + "]";
    }
    public Employee(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
}


Set<Employee> set = new HashSet<Employee>();
Employee e2 = new Employee(3,"Mohan");
Employee e3 = new Employee(4,"Shayam");
Employee e4 = new Employee(5,"rahul");
Employee e = new Employee(1,"rahul");
Employee e1 = new Employee(2,"ram");

How can I sort this HashSet when the hashset contain some user defined objects?

Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
TKD
  • 9
  • 2
  • A HashSet can't be sorted. You can create a list containing the same elements as the set, and sort that list. Google for "how to sort objects in Java", since this question has already been asked a million times. – JB Nizet Sep 27 '17 at 11:11
  • Also look at: https://stackoverflow.com/questions/22391350/how-to-sort-a-hashset – Klas Lindbäck Sep 27 '17 at 11:14

0 Answers0