I have one bean array, which has 3 properties. let us suppose from DB we got 10 records and which will be stored in the bean class. so basically it will become bean array. Now what I need is while displaying First Group by one column and then Sort by another column. Output should be in below format
[can any one please give suggestion on this?
Joined: Apr 23, 2007
heyyy any one please help me......................
Sort by the secondary column first and then sort by the primary column.
Joined: Apr 23, 2007
But what i need is different. First this must be sorted based on Status column. then if we have same status (like "damaged" 2 times in the table shown) ,then those 2 rows must be sorted based on 2nd column........ This is what I want ..
Rob's solution will work but has the disadvantage that you always sort by the second column. This could be a problem with larger datasets. I prefer to use a simple algorithm that only compares the additional columns when it needs to.
I would probably create a Comparator class. In its compare method I would implement code such as the following:
if obj1.columnA equals obj2.columnA
//first column equal so return comparison of second column
return obj1.columnB compareTo obj2.columnB
return obj1.columnA compareTo obj2.columnB
Then I would call either Arrays.sort or Collections.sort on your list making sure to use the Comparator you created.
See the Collections Framework for how to implement the sort if you are not familiar with the sorting functionality of Arrays/Collections. Also have a look at the Arrays and Collections utility classes in the java API docs.
Try to understand how the sort mentioned above will work first but if sorting by multiple columns then I tend to use the CompareToBuilder of the Apache Commons Lang package as it makes the code much simpler to understand.
Joined: Jun 13, 2009
let us suppose from DB we got 10 records
Thats why I kept it simple.
I prefer to use a simple algorithm that only compares the additional columns when it needs to
to be different from "I will only ever have 10 records" hence my suggestion for a different solution for larger datasets.
I had a read through the GroupComparator post and it should work fine but has the disadvantage that you must define a Comparator for each field you want to group by - maybe not ideal if you just want to use the natural ordering of Strings/Integers etc.
Thats where the CompareToBuilder comes in, it has multiple append methods where the natural ordering of objects (Comparable) can be used or alternatively you can specify a Comparator. So the Comparator for "status" then "number" would be as simple as:
subject: First Group by one column and then by sorting by another column