This week's giveaway is in the EJB and other Java EE Technologies forum.
We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line!
See this thread for details.
The moose likes Java in General and the fly likes sorting of a list having bean object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "sorting of a list having bean object" Watch "sorting of a list having bean object" New topic
Author

sorting of a list having bean object

Pawanpreet Singh
Ranch Hand

Joined: Jun 12, 2005
Posts: 264

I want to sort a List having bean CTVo based on its group Name.
Could any body provide me a solution using Comparator.

import java.util.*;

public class Test {
public static void main(String[] args){
List list = new LinkedList();
CTVo vo = new CTVo();
vo.setGroupId("1");
vo.setGroupId("Fill");
list.add(vo);

vo = new CTVo();
vo.setGroupId("1");
vo.setGroupId("Fill");
list.add(vo);

vo = new CTVo();
vo.setGroupId("1");
vo.setGroupId("Fill");
list.add(vo);

Collections.sort(list);
for(int i=0;i<list.size();i++){
CTVo result = new CTVo();

System.out.println(result.getGroupName());
}
}
}
class CTVo{
private String groupId;
private String groupName;
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
}
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
Try the comparable or the comparator interface.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I agree with Anupam. Either make your CTVo class implement the Comparable interface, or make a custom Comparator which you will pass to sort(List list, Comparator c).
Look for documentation about those classes, and try to figure out yourself how it works. Ask more if you still don't understand how Comparator/Comparable work
Here is a place you could start with : http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html


[My Blog]
All roads lead to JavaRanch
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Please keep to the topic of this forum, SCJP. We have our Java In General forums for, you guessed it, general programming problems.


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: sorting of a list having bean object
 
Similar Threads
Help me in understanding a code with one to many
Please give responses..
Changing a component's properties from a bean
Subdividing a Collection into smaller collections