簡體   English   中英

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

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

我有一個實現Comparable<Recipe>的對象Recipe

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

我已經這樣做了所以我能夠按以下方法按字母順序對List進行排序:

public static Collection<Recipe> getRecipes(){
    List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values());
    Collections.sort(recipes);
    return recipes;
}

但是現在,在另一種方法中,讓我們將其getRecipesSort() ,我想對數據進行排序,但是數字,比較包含其ID的變量。 更糟糕的是,ID字段的類型為String

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

使用此方法Collections.sort(List,Comparator) 實現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());
    }
}

然后使用Comparator作為

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

使用Lambda表達式可以使NINCOMPOOP給出的答案更簡單:

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

Java 8之后還介紹了Comparator接口中的比較器構造方法。 使用這些,可以進一步將其減少到1

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

1布洛赫,J. 有效的Java( 第三版 )。 2018.項目42,p。 194。

創建一個比較器,在其構造函數中接受比較模式,並根據您的要求為不同的場景傳遞不同的模式

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

}

實際上對於數字你需要單獨處理它們檢查下面

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
}

如果要對自然順序以外的其他內容進行排序,請使用接受Comparator的方法。

Collections.sort(List,Comparator)

按升序對未排序的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