0

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
myClass.setName("John");
myClass.setId("100");

myClassList.add(myClass);

myClass.setName("Arnold");
myClass.setId("101");


myClassList.add(myClass);


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

Now how do i sort myClassList based on Name.

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by BestJewSinceJC
Featured Replies
  • Implement the Comparable interface. [url]http://onjava.com/pub/a/onjava/2003/03/12/java_comp.html[/url] [url]http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html[/url] Then use the Collections.sort(yourArrayList) method [url]http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29[/url] 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 … Read More

1

Implement the Comparable interface.
http://onjava.com/pub/a/onjava/2003/03/12/java_comp.html
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Comparable.html

Then use the Collections.sort(yourArrayList) method
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html#sort%28java.util.List%29

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 by BestJewSinceJC: n/a

Comments
Nice resource
0

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?

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.