对于列表,我们使用该Collections.sort(List)方法.如果我们想要排序HashSet怎么办?
我有一个Recipe实现的对象Comparable<Recipe>:
public int compareTo(Recipe otherRecipe) {
return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName);
}
Run Code Online (Sandbox Code Playgroud)
我已经这样做了所以我能够List按以下方法按字母顺序排序:
public static Collection<Recipe> getRecipes(){
List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values());
Collections.sort(recipes);
return recipes;
}
Run Code Online (Sandbox Code Playgroud)
但是现在,在另一种方法中,让我们调用它getRecipesSort(),我想要对数据进行排序,但数字,比较包含其ID的变量.更糟糕的是,ID字段属于类型String.
如何使用Collections.sort()在Java中执行排序?