我有一个Recipe实现的对象Comparable<Recipe>:
Recipe
Comparable<Recipe>
public int compareTo(Recipe otherRecipe) { return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName); }
我这样做了,因此可以List使用以下方法按字母顺序排序:
List
public static Collection<Recipe> getRecipes(){ List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values()); Collections.sort(recipes); return recipes; }
但是现在,以另一种方法命名为getRecipesSort(),我想对同一列表进行排序,但以数字方式比较包含ID的变量。更糟的是,ID字段的类型为String。
getRecipesSort()
String
如何使用Collections.sort()在Java中执行排序?
使用此方法Collections.sort(List,Comparator)。实施比较器并将其传递给Collections.sort().
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()); } }
然后使用Comparatoras
Comparator
Collections.sort(recipes,new RecipeCompare());