• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting the collection By a field dynamically  RSS feed

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've a list of Student objects

List<Student> studentList;

class Student {
private String field1;
private String field2;
private String field3;
private String field4;
}

I want to sort this studentList dynamically by a given field name.

If I give (studentList, field1), the collection should be sorted based on field1.
If I give (studentList, field2), the collection should be sorted based on field2.


Is there any simple and best way to achieve the same?
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, a Comparator.
 
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out Collections#sort()

Better suited for intermediate. Moving.
 
Ranch Hand
Posts: 2458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Google "DtoComparator". You'll find at least an example.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!