簡體   English   中英

使用帶有自定義比較器的reverseOrder()以降序對列表進行排序?

[英]Sorting a List in descending order using reverseOrder() with custom Comparator?

我有Supplier類型的以下對象列表,我想使用reverseOrder()方法對它們進行排序(因此它們將按降序排列)。 但是,在互聯網上閱讀了一整天之后,我仍然無法正常工作。 我非常確定這是我在這里所缺少的很小的東西。 升序的自然順序可以正常工作。

這是我的Supplier類別:

public class Supplier  {
    private String supplierName = "";
    private String representative = "";
    private String representativesPhoneNumber = "";

    private Map<Drug, Integer> listOfDrugs = new HashMap<Drug, Integer>();

    Supplier(String n, String rep, String repPhoneNum, String drugName, double drugPrice, int stock) {
        this.supplierName = n;
        this.representative = rep;
        this.representativesPhoneNumber = repPhoneNum;
        listOfDrugs.put(new Drug(drugName, drugPrice), stock);
    }

    public Map<Drug, Integer> getListOfDrugs() {
        return this.listOfDrugs;
    }

    public static Integer getKeyExtractor(Supplier supplier, Drug drug) {
        return Optional.ofNullable(Optional.ofNullable(supplier.getListOfDrugs())
                                   .orElseThrow(() -> new IllegalArgumentException("drugs is null")).get(drug))
                       .orElseThrow(() -> new IllegalArgumentException("the drug couldn't be found"));
    }
}

如果對象<Drug, Integer> ,則具有Map 這是我的Drug課:

public class Drug {
    private String name = "";
    private double price = 0.0;

    Drug(String n, double p) {
        this.name = n;
        this.price = p;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Drug other = (Drug) obj;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
            return false;
        return true;
    }
}

出於垃圾郵件的考慮,大部分代碼都經過了修整。 :)

還有我的Orders類,我實際上在其中進行排序:

public class Orders {
    private Map <Drug, Integer> orderedDrugs = new HashMap <Drug, Integer>();
    private Vector<Supplier> suppliers = new Vector <Supplier>();   

    public void sort(Drug drug, List<Supplier> sortedSuppliers) {
        Collections.sort(suppliers, Comparator.comparing(s -> Supplier.getKeyExtractor(s, drug), Comparator.reverseOrder()));   
    }

    public List<Supplier> getSortedSuppliersByQuantity(Drug drug) {
        List <Supplier> sortedSuppliers = new ArrayList <Supplier>();
        for(Supplier s : suppliers) {
            for(Entry<Drug, Integer> entry : s.getListOfDrugs().entrySet()) {
                if(entry.getKey().getDrugsName().equals(drug.getDrugsName()));
                    sortedSuppliers.add(s);
            }
        }
        sort(drug, sortedSuppliers);
        return sortedSuppliers;
    }
}

再次修剪代碼,僅顯示實際問題所需的方法。

所以到目前為止,我已經嘗試過:

  1. Collections.sort(suppliers, Comparator.comparing(s -> Supplier.getKeyExtractor(s, drug), Comparator.reverseOrder()));

  2. Collections.sort(suppliers, Collections.reverseOrder(Comparator.comparing(s -> Supplier.getKeyExtractor(s, drug))));

但是兩者都不起作用。 我需要在某個地方實現compareTo()還是缺少某種方法? 由於升序有效,但不降序。

Collections.sort(suppliers, Comparator.comparing(s -> Supplier.getKeyExtractor(s, drug))); 將它們按升序排序並工作。

感謝您的提前幫助,對於冗長的帖子,我們深表歉意!

更新:

我也嘗試在Supplier類中實現compareTo ,但是得到了NPE。 :/

public int compareTo(Supplier a) {
    for(Entry<Drug, Integer> entry : listOfDrugs.entrySet()) {
        int result = listOfDrugs.get(entry.getKey()).compareTo(a.listOfDrugs.get(entry.getKey()));
        if(result != 0)
            return result;
    }
    return 0;
}

嘗試

Collections.sort(suppliers, 
                 Comparator.comparing((Supplier s) -> Supplier.getKeyExtractor(s, drug)).reversed());

我構建了一個簡化的版本,並且可以正常工作。 我沒有在您的Supplier等類上嘗試過。

好的,我找到了解決該問題的方法,因為其他所有內容都不適合我。 使用sort方法對列表進行升序sort ,我只需調用: Collections.reverse(myList); 然后得到降序排列的列表。 我知道這可能很la腳,但是對我有用。

是的,您需要。 實現Comparator (並根據需要對其進行調整),並調用sort方法。

更新:要使用lambda表達式進行操作,請嘗試按此處所示進行操作。

更新#2:

下面是我想出的。 希望能幫助到你 :

    /**
Input:[9, 9, 5, 1, 6, 3, 9, 4, 7, 1]
Reversed:[1, 7, 4, 9, 3, 6, 1, 5, 9, 9]
ReverseOrdered:[9, 9, 9, 7, 6, 5, 4, 3, 1, 1]
     */
    private static void testCollectionsSort() {

        List<Integer> integerList = new ArrayList<>();
        int size=10;
        Random random = new Random();
        for(int i=0;i<size;i++) {
            integerList.add(random.nextInt(size));
        }

        System.out.println("Input:"+integerList);
        List<Integer> integerListTwo = new ArrayList<>(integerList);
        Collections.reverse(integerListTwo);
        System.out.println("Reversed:"+integerListTwo);
        Comparator<Integer> integerComparator = (Integer a, Integer b) -> b.compareTo(a); // 'b' is compared to 'a' to enable reverse
        Collections.sort(integerList, integerComparator);

        System.out.println("ReverseOrdered:"+integerList);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM