2013-05-07 17 views
31

tôi có một đối tượng Recipe mà thực hiện Comparable<Recipe>:Làm thế nào để sử dụng Collections.sort() trong Java? (Tình hình cụ thể)

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

tôi đã làm điều đó vì vậy tôi có thể sắp xếp các List theo thứ tự abc bằng phương pháp sau:

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

Nhưng bây giờ, theo một phương pháp khác, cho phép gọi nó là getRecipesSort(), tôi muốn sắp xếp cùng một danh sách nhưng bằng số, so sánh một biến chứa ID của chúng. Để làm mọi việc tồi tệ hơn, trường ID là loại String.

+1

http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html –

+1

@BrianRoach Tôi xin lỗi nếu tôi không đáp ứng được yêu cầu của bạn để trả lời. Tôi biết tài liệu ở đâu, tôi chỉ tìm kiếm các giải pháp sáng tạo, vì tôi không thể tìm thấy bất kỳ giải pháp nào. Bỏ phiếu xuống chỉ là hoàn toàn vô lý nhưng ồ, không thể giải thích được sự thất vọng. – jsfrocha

Trả lời

47

Sử dụng phương pháp này Collections.sort(List,Comparator). Thực hiện một Comparator và vượt qua nó để 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()); 
    } 
} 

Sau đó sử dụng Comparator như

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

Hầu hết.OP muốn so sánh dựa trên các trường ID, là các chuỗi, nhưng để so sánh chúng với số lượng. Chúng ta không biết phạm vi, nhưng nếu chúng phù hợp với ints thì chuyển sang int và so sánh sẽ hoạt động, nếu không một kiểu thích hợp sẽ phải được chọn hoặc một bộ so sánh phức tạp hơn, nhưng đây là cách tiếp cận đúng. –

+0

Thực ra, tôi giống như sự đơn giản của câu trả lời này, nó làm tôi nghĩ tôi sẽ làm thế nào, bây giờ tôi đang làm việc. – jsfrocha

3

Sử dụng phương pháp mà chấp nhận một Comparator khi bạn muốn sắp xếp trong một cái gì đó khác hơn là trật tự tự nhiên.

Collections.sort(List, Comparator)

5

Tạo một so sánh mà chấp nhận chế độ so sánh trong constructor của nó và vượt qua chế độ khác nhau cho các kịch bản khác nhau dựa trên yêu cầu của bạn

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

}

Trên thực tế đối với số lượng bạn cần để xử lý họ kiểm tra riêng bên dưới

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 
} 
14

Câu trả lời được đưa ra bởi người ngớ ngẫn thể được thực hiện đơn giản bằng Lambda Expressions:

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

Cũng giới thiệu sau Java 8 là biện pháp thi công so sánh trong giao diện Comparator. Sử dụng những điều kiện này có thể tiếp tục giảm xuống còn :

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

Bloch, J. Effective Java (3 thứ Edition). 2018. Khoản 42, tr. 194.

0

Sắp xếp hashmap chưa phân loại theo thứ tự tăng dần.

// 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()); 
    } 
Các vấn đề liên quan