如何在 Java 中使用 Collections.sort()? [英] How to use Collections.sort() in Java?

查看:34
本文介绍了如何在 Java 中使用 Collections.sort()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象 Recipe 实现了 Comparable :

I got an object Recipe that implements Comparable<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?

推荐答案

使用此方法 Collections.sort(List,Comparator).实现一个 Comparator 并将其传递给 Collections.sort().

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆