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?
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With