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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16425127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:52:03  来源:igfitidea点击:

How to use Collections.sort() in Java?

javasortingspring-mvccollections

提问by jsfrocha

I got an object Recipethat implements Comparable<Recipe>:

我得到了一个Recipe实现的对象Comparable<Recipe>

public int compareTo(Recipe otherRecipe) {
    return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName);
}

I've done that so I'm able to sort the Listalphabetically 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. To make things worse, the ID field is of the type String.

但是现在,在不同的方法中,让我们调用它getRecipesSort(),我想对相同的列表进行排序,但按数字排序,比较包含其 ID 的变量。更糟糕的是,ID 字段的类型是String

How do I use Collections.sort() to perform the sorts in Java?

如何使用 Collections.sort() 在 Java 中执行排序?

采纳答案by NINCOMPOOP

Use this method Collections.sort(List,Comparator). Implement a Comparatorand pass it to Collections.sort().

使用此方法Collections.sort(List,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 Comparatoras

然后使用Comparator作为

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

回答by John B

Use the method that accepts a Comparatorwhen you want to sort in something other than natural order.

Comparator当您想以非自然顺序排序时,请使用接受 a 的方法。

Collections.sort(List, Comparator)

Collections.sort(列表,比较器)

回答by threadfin

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
}

回答by Gyanesh Sharma

The answer given by NINCOMPOOPcan be made simpler using Lambda Expressions:

使用 Lambda 表达式可以简化NINCOMPOOP给出的答案:

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

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

Also introduced after Java 8 is the comparator construction methods in the Comparatorinterface. Using these, one can further reduce this to1:

Java 8 之后还引入了Comparator接口中的比较器构造方法。使用这些,可以进一步将其减少到1

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


1Bloch, J. Effective Java(3rdEdition). 2018. Item 42, p. 194.

1布洛赫,J.有效的Java(3版)。2018 年。第 42 项,第 4 页。194.

回答by Kashan

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