Monday, April 28, 2014

Using Collections.sort() with Comparator to sort ArrayList

Person.java
package javapeople;

public class Person {

    private String surname;
    private String name;

    public Person(String name, String surname) {
        this.surname = surname;
        this.name = name;
    }

    public String getSurname() {
        return surname;
    }
    
    public String getName() {
        return name;
    }

    public String toString() {
        return name + " " + surname;
    }

}

SortBySurname.java
package javapeople;

import java.util.Comparator;

public class SortBySurname implements Comparator <Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getSurname().compareTo(o2.getSurname());
    }
    
}

SortByName.java
package javapeople;

import java.util.Comparator;

public class SortByName implements Comparator <Person>{

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getName().compareTo(o2.getName());
    }
    
}

JavaPeople.java
package javapeople;

import java.util.ArrayList;
import java.util.Collections;

/**
 * @web java-buddy.blogspot.com
 */
public class JavaPeople {

    public static void main(String[] args) {
        ArrayList<Person> peopleList = new ArrayList<>();
        peopleList.add(new Person("Albert", "Einstein"));
        peopleList.add(new Person("Isaac", "Newton"));
        peopleList.add(new Person("Thomas", "Edison"));
        peopleList.add(new Person("Charles", "Darwin"));
        peopleList.add(new Person("James", "Watt"));
        
        System.out.println("Unsorted:");
        System.out.println(peopleList);
        
        Collections.sort(peopleList, new SortBySurname());
        System.out.println("Sorted by Surname:");
        System.out.println(peopleList);
        
        Collections.sort(peopleList, new SortByName());
        System.out.println("Sorted by Name:");
        System.out.println(peopleList);
    }

}


No comments:

Post a Comment