简体   繁体   English

如何在Java中使用Collections.sort()?

[英]How to use Collections.sort() in Java?

I got an object Recipe that implements Comparable<Recipe> : 我有一个实现Comparable<Recipe>的对象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: 我已经这样做了所以我能够按以下方法按字母顺序对List进行排序:

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. 但是现在,在另一种方法中,让我们将其getRecipesSort() ,我想对数据进行排序,但是数字,比较包含其ID的变量。 To make things worse, the ID field is of the type String . 更糟糕的是,ID字段的类型为String

How do I use Collections.sort() to perform the sorts in Java? 如何使用Collections.sort()在Java中执行排序?

Use this method Collections.sort(List,Comparator) . 使用此方法Collections.sort(List,Comparator) Implement a Comparator and pass it to Collections.sort(). 实现Comparator并将其传递给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 然后使用Comparator作为

Collections.sort(recipes,new RecipeCompare());

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions: 使用Lambda表达式可以使NINCOMPOOP给出的答案更简单:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Java 8之后还介绍了Comparator接口中的比较器构造方法。 Using these, one can further reduce this to 1 : 使用这些,可以进一步将其减少到1

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3 rd Edition). 1布洛赫,J. 有效的Java( 第三版 )。 2018. Item 42, p. 2018.项目42,p。 194. 194。

Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement 创建一个比较器,在其构造函数中接受比较模式,并根据您的要求为不同的场景传递不同的模式

public class RecipeComparator implements Comparator<Recipe> {

public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;

private int compare_mode = COMPARE_BY_NAME;

public RecipeComparator() {
}

public RecipeComparator(int compare_mode) {
    this.compare_mode = compare_mode;
}

@Override
public int compare(Recipe o1, Recipe o2) {
    switch (compare_mode) {
    case COMPARE_BY_ID:
        return o1.getId().compareTo(o2.getId());
    default:
        return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
    }
}

} }

Actually for numbers you need to handle them separately check below 实际上对于数字你需要单独处理它们检查下面

public static void main(String[] args) {
    String string1 = "1";
    String string2 = "2";
    String string11 = "11";

    System.out.println(string1.compareTo(string2)); 
    System.out.println(string2.compareTo(string11));// expected -1 returns 1
   // to compare numbers you actually need to do something like this

    int number2 = Integer.valueOf(string1);
    int number11 = Integer.valueOf(string11);

    int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
    System.out.println(compareTo);// prints -1
}

Use the method that accepts a Comparator when you want to sort in something other than natural order. 如果要对自然顺序以外的其他内容进行排序,请使用接受Comparator的方法。

Collections.sort(List, Comparator) Collections.sort(List,Comparator)

Sort the unsorted hashmap in ascending order. 按升序对未排序的hashmap进行排序。

// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) 
{
                return o2.getValue().compareTo(o1.getValue());
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM