Hi guys, I was trying to sort an arrayList using a comparator but I didn't have much luck, or at least it seems like there is something slightly wrong with it.
I have these objects in the arrayList
employeeCollection.add(new Employee("Dan", 112));
employeeCollection.add(new Employee("Tim", 2));
employeeCollection.add(new Employee("Rick", 11));
employeeCollection.add(new Employee("Jack", 19));
employeeCollection.add(new Employee("Sid", 1));
and before sorting I have this
Name: Dan:
ID number: 112:
Name: Tim:
ID number: 2:
Name: Rick:
ID number: 11:
Name: Jack:
ID number: 19:
Name: Sid:
ID number: 1:
and after sorting I have this:
Name: Dan:
ID number: 112:
Name: Jack:
ID number: 19:
Name: Rick:
ID number: 11:
Name: Sid:
ID number: 1:
Name: Tim:
ID number: 2:
so it didn't go that well. Here is the code I've used, and the questions are:
-why isn't this sorted properly?
-what would I need to do to sort it in ascending order
/*
* This tests Array list of employees*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestCollections {
private static List<Employee> employeeCollection = new ArrayList<Employee>();
public static void main(String[] args) {
createEmployees();
}
private static void createEmployees() {
// for(int i = 0; i < 10; i++) {
// Employee employee = new Employee("Jo_" + i, i);
// employeeCollection.add(employee);
// }
employeeCollection.add(new Employee("Dan", 112));
employeeCollection.add(new Employee("Tim", 2));
employeeCollection.add(new Employee("Rick", 11));
employeeCollection.add(new Employee("Jack", 19));
employeeCollection.add(new Employee("Sid", 1));
printEmployees();
//Collections.sort(employeeCollection);
// Sorting
Collections.sort(employeeCollection, new Comparator<Employee>() {
@Override
public int compare(Employee employee, Employee employee1)
{
return employee.getName().compareTo(employee1.getName());
}
});
printEmployees();
}
private static void printEmployees() {
employeeCollection.forEach(listItem -> System.out.println(listItem));
}
}
and the Employee class
public class Employee {
private String name;
private int idNumber;
public Employee(String name, int idNumber) {
this.name = name;
this.idNumber = idNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
@Override
public String toString() {
return String.format("%s: %s: \n%s: %d:", "Name", getName(), "ID number", getIdNumber());
}
// Overriding the compareTo method
public int compareTo(Employee employee) {
return (this.name).compareTo(employee.name);
}
// Overriding the compare method to sort the age
public int compare(Employee employee, Employee employee1) {
return employee.idNumber - employee1.idNumber;
}
}