Object ArrayList Sort

Let’s say we have a simple class called Person

public class Person{
	public String name;
	public int age;
	
	public Person(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
}

If you want to create an ArrayList of Person objects and sort it by name you can do the following:

// populate the ArrayList with some objects
ArrayList<Person> arpList = new ArrayList<TransgressionTab.Person>();

arpList.add(new Person("Onasis", 54));
arpList.add(new Person("Spartakus", 12));
arpList.add(new Person("Oneiro", 1));
arpList.add(new Person("Bomb", 12));

// sort it
Collections.sort(arpList,new Comparator<Person>() {
	@Override
	public int compare(Person s1,Person s2) {
		return s1.name.compareToIgnoreCase(s2.name);
	}
});
Advertisements

About cmanios

programming
This entry was posted in Java and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s