Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Collections.sort() in Java?

I got an object Recipe that implements Comparable<Recipe> :

public int compareTo(Recipe otherRecipe) {     return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName); } 

I've done that so I'm able to sort the List alphabetically in the following method:

public static Collection<Recipe> getRecipes(){     List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values());     Collections.sort(recipes);     return recipes; } 

But now, in a different method, lets call it getRecipesSort(), I want to sort the same list but numerically, comparing a variable that contains their ID. To make things worse, the ID field is of the type String.

How do I use Collections.sort() to perform the sorts in Java?

like image 893
jsfrocha Avatar asked May 07 '13 17:05

jsfrocha


People also ask

How do you sort a collection in Java?

The sorted() Method in Java The sorted() method used to sort the list of objects or collections of the objects in the ascending order. If the collections of the objects are comparable then it compares and returns the sorted collections of objects; otherwise it throws an exception from java. lang.

What is the use of Collections sort?

By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.


1 Answers

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {      @Override     public int compare(Recipe o1, Recipe o2) {         // write comparison logic here like below , it's just a sample         return o1.getID().compareTo(o2.getID());     } } 

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare()); 
like image 150
AllTooSir Avatar answered Sep 20 '22 21:09

AllTooSir