1

The following is the Employee bean class.

public class Employee {
    public String name;
    public int age;

    public Employee()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }
}

I have other EmployeeTest class and inside it I create the object of the Employee class and store in a ArrayList.

import java.util.ArrayList;

public class EmployeeTest {
    public static void main(String[] args) 
    {
        ArrayList<Employee> empList = new ArrayList<Employee>();
        Employee emp1 = new Employee();
        emp1.setAge(15);
        emp1.setName("Employee1");
        Employee emp2 = new Employee();
        emp2.setAge(10);
        emp2.setName("Employee1");
        empList.add(emp1);
        empList.add(emp2);
        for(Employee emp : empList)
        {
            System.out.println("employee name : " + emp.getName());
            System.out.println("employee age : " + emp.getAge());
        }
    }
}

Now I have one question regarding it is that I want to sort ArrayList on the basis of Employee class age property. So please explain how can I sort it.

Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
Rohit
  • 233
  • 2
  • 4
  • 8

7 Answers7

10

Letting the class implement the Comparable interface, as suggested in the other answers, is one option.

But in general, I'd recommend to NOT implement the Comparable interface, as long as the class does not have an undoubted natural ordering. And for Employee, there is certainly NO natural ordering.

Imagine you want to sort the Employees according to their age. Once in ascending order, and once in descending order. How could you do that? Now imagine you want to sort them once by their age, and once alphabetically, by their first name. You could not do this, without implementing a Comparator. And that's what I'd recommend here:

You can create a method like

private static Comparator<Employee> byAge()
{
    return new Comparator<Employee>()
    {
        @Override
        public int compare(Employee o1, Employee o2)
        {
            return o1.getAge() - o2.getAge();
        }
    };        
}

Then you can simply call

Collections.sort(empList, byAge());

If you want to sort them in reverse order, you can call

Collections.sort(empList, Collections.reverseOrder(byAge()));

If you want to sort them by their name, you can create a method

private static Comparator<Employee> byName()
{
    return new Comparator<Employee>()
    {
        @Override
        public int compare(Employee o1, Employee o2)
        {
            return o1.getName().compareTo(o2.getName());
        }
    };        
}

And sort them with

    Collections.sort(empList, byName());

This is much more versatile than implementing Comparable.

Marco13
  • 53,703
  • 9
  • 80
  • 159
  • Great answer! Explains not just what to do, but why to do it this way. – Nigel Tufnel Feb 09 '14 at 14:01
  • @Marco13 or Nigel I want to just confirm that is the same way would be used if I use the HashSet instead of ArrayList? I know it is simple question but any kind of help would be appreciated. – Rohit Feb 09 '14 at 14:32
  • A HashSet can not be sorted. A TreeSet could be sorted, but due to the constraints that apply there (namely, that the elements must be unique according to the sorting criterion), this can hardly be used here. – Marco13 Feb 09 '14 at 14:57
  • please review is it right way to do that. TreeSet empSet = new TreeSet(new Comparator() { @Override public int compare(Employee o1, Employee o2) { return o1.getAge() - o2.getAge(); } }); empSet.add(emp1); empSet.add(emp2); empSet.add(emp3); for(Employee emp : empSet) { System.out.println("employee name : " + emp.getName()); System.out.println("employee age : " + emp.getAge()); } – Rohit Feb 09 '14 at 15:18
  • You may **NOT** put the elements into a TreeSet this way. When you do this, it roughly means that there may not be two employees with the same age! (It may cause further problems, but that's the basic idea). Also see the definition of a comparator being "*consistent with equals*" on http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html BTW: The comments are not the right place to post code. – Marco13 Feb 09 '14 at 15:44
2

You can use the Collections.sort method with a custom Comparator:

 import java.util.Collections;
 import java.util.Comparator;

 [...]

 Collections.sort(empList, new Comparator<Employee>() {
                @Override public int compare(Employee x, Employee y) {
                   return Integer.compare(x.getAge(), y.getAge());
                }
            });

I used anonymous Comparator class, you can also write an ordinary Comparator class, see Sri Harsha Chilakapati answer.

Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31
1

Implement Comparable interface

class Employee implements Comparable<Employee> {   

Add implement the method compareTo in Employee class like this:

 @Override
 public int compareTo(Employee other) {
     return this.age - other.age;
 }

Then you can sort your list like here:

Collections.sort(empList)
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28
1

You need to write a Comparator.

class EmployeeAgeComparator implements Comparator<Employee>
{
    @Override
    public int compare(Employee e1, Employee e2)
    {
        if (e1.getAge() > e2.getAge())
        {
            return -1;
        } 
        else if (e1.getAge() < e2.getAge())
        {
            return 1;
        }
        return 0;
    }
}

Then use Collections.sort method like this.

Collections.sort(empList, new EmployeeAgeComparator());

Hope this helps.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91
0

Your class has to implement Comparable interface and implements compareTo method. Then you can use Arrays.sort(yourArray) to sort it.

wawek
  • 1,577
  • 1
  • 13
  • 23
0

I think you might want to sort on different properties, so in that case you should create the appropriate Comparators and use that with the proper sort method (the one which requires that too).

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52
0

This is a simple sorting algorithm. We store the subscript value of the lowest age so we can swap it.

for (int i = 0; i < empList.size(); i++)
        {
            int smallest = i;
            for (int j = i; j < numbers.length; j++)
            {
                if (empList.get(j).getAge() < emplist.get(smallest).getAge())
                    smallest = j;
            }

            int temp = empList.get(i).getAge();

            empList.set(i, empList.get(smallest))
            empList.set(smallest, temp);
        }
Whoppa
  • 949
  • 3
  • 13
  • 23