如何在Java中使用Collections.sort()? [英] How to use Collections.sort() in Java?
本文介绍了如何在Java中使用Collections.sort()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个实现Comparable<Recipe>
的对象Recipe
:
public int compareTo(Recipe otherRecipe) {
return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName);
}
我这样做是为了能够按以下方法按字母顺序对List
进行排序:
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;
}
但是现在,以另一种方法命名为getRecipesSort()
,我想对同一列表进行排序,但以数字方式比较包含其ID的变量.更糟的是,ID字段的类型为String
.
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
.
如何使用Collections.sort()在Java中执行排序?
How do I use Collections.sort() to perform the sorts in Java?
推荐答案
使用此方法比较器并将其传递给
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());
}
}
然后将Comparator
用作
Collections.sort(recipes,new RecipeCompare());
这篇关于如何在Java中使用Collections.sort()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文