Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sorting of a list having bean object

 
Pawanpreet Singh
Ranch Hand
Posts: 264
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try the comparable or the comparator interface.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please keep to the topic of this forum, SCJP. We have our Java In General forums for, you guessed it, general programming problems.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic