Hi Everyone,
I am searching the most effective way of sorting a list of objects.

Say i have a bean

public class MyClass {
	private string name;
	private string id;
	// Getters and setters

Now say we put some values in a List

List<MyClass> myClassList  = new ArrayList<MyClass>();

MyClass myClass = new MyClass();

//In some iterator adding items to the list




// Say now my list has two entries of myClass object.

Now how do i sort myClassList based on Name.

Implement the Comparable interface.

Then use the Collections.sort(yourArrayList) method

In fact the first link shows the whole process. If you are good at reading method documentation all you need to do is look at the second link, implement that interface (it only has one method), then call Collections.sort(yourArrayList). Otherwise just read the first link and follow directions.

Edited 6 Years Ago by BestJewSinceJC: n/a

Nice resource

Awesome. Indeed the first link is a good resource for anyone trying to learn sorting.Thanks a lot BestJewSinceJC

But i have a little problem. I wont be able to modify my bean "MyClass" as it will be an existing object from the product i am using. So any other idea?

Make a class that extends the MyClass, then implement the Comparable interface on that class instead. Basically do the exact same thing, except you'll have to extend MyClass as well.

This article has been dead for over six months. Start a new discussion instead.