Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

sorting - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...