簡體   English   中英

根據Java中的參數值對對象列表進行排序

[英]Sort list of objects based on a parameter value in Java

我有對象列表,並且該對象的結構定義如下:

class PredicateInfo {
    String predicateName;
    String predicateStatus;
}

在這里,predicateName可以是任何有效的字符串,而predicateStatus可以是以下值中的任何一個:VERIFIED,IN_PROGRESS,UNVERIFIED,NOT_INITIATED。

Priority of these strings: 
Priority 1: VERIFIED
Priority 2: IN_PROGRESS
Priority 3: UNVERIFIED
Priority 4: NOT_INITIATED

在這里,我有一個用例,我想基於predicateStatus對List [PredicateInfo]進行排序。 例如:

Input list:
List[ PredicateInfo("A", "IN_PROGRESS"), PredicateInfo("A", "VERIFIED")]
Output:
List[ PredicateInfo("A", "VERIFIED"), PredicateInfo("A", "IN_PROGRESS")]

一種簡單的解決方案是反復遍歷以獲得排序后的列表,我正在嘗試尋找其他替代方法來實現相同的目的。

使用Java的Comparator實現以下目的:

public Comparator<PredicateInfo> PredicateInfoComparator 
                      = new Comparator<PredicateInfo>() {

    public int compare(PredicateInfo info1, PredicateInfo info2) {

      //your sorting logic here
    }

};

並使用以下命令調用它:

Collections.sort(list, new PredicateInfoComparator());

如Javadoc所述,排序邏輯應返回負整數,零或正整數,因為第一個參數小於,等於或大於第二個參數。 有關完整的Javadoc,請參見此處

另外, PredicateInfo可以實現Comparable接口,並且可以調用sorting調用:

Collections.sort(list);

這將隱式調用該方法compareTo中聲明Comparable 更多細節在這里

您可以將比較器傳遞給sort方法。

List<String> predicateStatuses = new ArrayList<>();
predicateStatuses.add("VERIFIED");
predicateStatuses.add("IN_PROGRESS");
predicateStatuses.add("UNVERIFIED");
predicateStatuses.add("NOT_INITIATED");


predicateInfos.sort(Comparator.<PredicateInfo>comparingInt(predicateInfo -> predicateStatuses.indexOf(predicateInfo.getPredicateStatus()))
            .thenComparing(PredicateInfo::getPredicateName));

比較器功能的邏輯是:

首先,按predicateStatus字符串在predicateStatuses列表中的位置排序。 這是您提供的順序(或優先級)。 因此,具有predicateStatus = VERIFIEDPredicateInfo對象將在輸出中排在第一位。

接下來,對於相同的對象predicateStatus的由自然排序(字典)排序predicateName

Ideone演示

對於列表中的值:

Map<Integer, String> priorityMap = new HashMap<>();
priorityMap.put(1, "VERIFIED");
priorityMap.put(2, "IN_PROGRESS");
priorityMap.put(3, "UNVERIFIED");
priorityMap.put(4, "NOT_INITIATED");

Collections.sort(inputList, new Comparator<PredicateInfo >() {
      @Override
      public int compare(PredicateInfo obj1, PredicateInfo obj2) {
        return priorityMap.get(obj1.getPredicateStatus()) - priorityMap.get(obj2.getPredicateStatus())
      }
    });

這會給你一個排序列表

暫無
暫無

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

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