Emmet McLaughlin
Emmet McLaughlin

Reputation: 142

Sort names in Java ArrayList?

I have an arraylist containing names, ages, salaries, etc.

I want to sort the list by name.

The following is what I have in my class:

//Sort by Name
public ArrayList<Employee> sortByName()
{
  Collections.sort(employees);
  return employees;
}

I have a comparator (which I'm not sure is even being used) here:

import java.util.*;

public class EmployeeNameComparator implements Comparator<Employee>
{
   ArrayList<Employee> employees = new ArrayList<Employee>();

   //METHODS
   //Name Compare
   public int compare(Employee object1, Employee object2)
   {
      return object1.getName().compareTo(object2.getName());
   }
}

And here are the relevant parts of the tester I've made:

CompanyDataBase database = new CompanyDataBase();

  database.addEmployee(new Employee("John James", 34, 45000));
  database.addEmployee(new Employee("Josie Gibson", 19, 19000));
  database.addEmployee(new Employee("Luke Marsden", 28, 30000));
  database.addEmployee(new Manager("Aaron Morgan", 28, 44000, 5500));

  System.out.println("\n\nSORT BY NAME");
  //Collections.sort(database.getEmployees());
  database.sortByName();

  for(Employee currEmployee: database.getEmployees())
  {
     System.out.println(currEmployee.getDescription());
  }

I've tried this loads of ways but nothing seems to be working, does anyone know where I'm going wrong or how to make it work? Thanks.

Upvotes: 2

Views: 989

Answers (2)

Roman C
Roman C

Reputation: 1

Sort objects by name using a comparator the second parameter required.

Collections.sort(employees, new EmployeeNameComparator());

See the example of using a custom comparator.

Upvotes: 4

Ralph
Ralph

Reputation: 120771

use the method Collections.sort(List<T> list, Comparator<? super T> c) to sort a collection with a given comparator

 Collections.sort(employees, new EmployeeNameComparator());

Upvotes: 3

Related Questions