Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...