Most examples you find of this are too simple and involve only Strings or Integers. Here's little more complex example. It's from some code I wrote to interface to AddressDoctor™, a commercial address verification service.
The important stuff to look at here is the block that begins
Collections.sort( ...
// fill the array...
.
.
.
List< ADAddressDto > suggestedDtos = queryResult.getAddressData();
/* Sort the suggestions from highest mailability to lowest if asked to do so,
* or if caller asks us to limit returned DTOs or cut them off based on a
* mailability threshold.
*
* If our caller limits the number of suggestions he wants back, then toss out
* any extra ones--always keeping those of highest mailability. Then, filter
* the results even further based on his expression of lowest acceptable
* mailability.
*/
boolean sortThem = proposed.sortSuggestions();
int keep = proposed.getMaximumSuggestions();
int lowest = proposed.getMailabilityThreshold();
if( sortThem || keep > 0 || lowest > 0 )
{
Collections.sort( suggestedDtos, new Comparator< ADAddressDto >()
{
@Override
public int compare( ADAddressDto o1, ADAddressDto o2 )
{
return ( o1.getMailability() < o2.getMailability() ) ? 1 : -1;
}
}
);
List< ADAddressDto > results = new ArrayList< ADAddressDto >();
for( ADAddressDto dto : suggestedDtos )
{
if( keep-- <= 0 )
break;
results.add( dto );
}
queryResult.setAddressData( results );
if( lowest != 0 )
{
// choke up on all that was passed back: it's potentially a shorter list now!
suggestedDtos = results;
results = new ArrayList< ADAddressDto >();
for( ADAddressDto dto : queryResult.getAddressData() )
{
if( dto.getMailability() < lowest )
break;
results.add( dto );
}
queryResult.setAddressData( results );
}
}
return queryResult;
}