2017-02-08 19 views
1

私が必要とするのは、カスタム方法でリストを注文することです。正しい方法を探して、GuavaのOrdering APIを見つけましたが、注文しているリストがいつも同じではないということです。部分的な明示的な注文と別の注文の注文?

public static class SupportedAccountsComparator implements Comparator<AccountType> { 
    Ordering<String> ordering = Ordering.explicit(ImmutableList.of("rrsp", "tfsa")); 
    @Override 
    public int compare(AccountType o1, AccountType o2) { 
     return ordering.compare(o1.type, o2.type); 
    } 
} 

:私は、グアバライブラリ内のカスタムコンパレータと使用して注文して、このような何かを試してみました

List<AccountType> accountTypes = new ArrayList<>(); 
AccountType accountType = new AccountType(); 
accountType.type = "tfsa"; 
AccountType accountType2 = new AccountType(); 
accountType2.type = "rrsp"; 
AccountType accountType3 = new AccountType(); 
accountType3.type = "personal"; 
accountTypes.add(accountType3); 
accountTypes.add(accountType2); 
accountTypes.add(accountType); 
//The order I might have is : ["personal", "rrsp", "tfsa"] 
//The order I need is first "rrsp" then "tfsa" then anything else 

:ちょうどたとえば、私はこれを持って、リストの一番上になるように2つのフィールドを必要とします明示的な順序付けがあなたが提供したリストにない他の項目をサポートしていないために例外をスローします。部分的な明示的なoを行う方法がありますラダー?

Ordering.explicit(ImmutableList.of("rrsp", "tfsa")).anythingElseWhatever(); 
+0

何あなただけの他のすべてのタイプのためにこれら二つのアカウントの種類の '1'と '2'と '0'になりAccountType' 'でプロパティ(' order'/'priority')を有していた場合は?そして主にそのプロパティに基づいて順序を定義します。 –

+0

[Guava:リストと単一の要素からの明示的な順序付けを作成する方法](http://stackoverflow.com/questions/14403114/guava-how-to-create-an-explicit-ordering-from) -a-list-and-a-single-element) –

答えて

1

これにはGuavaは必要ありません。必要なものはすべてCollections APIにあります。

Comparator<AccountType> comparator = (o1, o2) -> { 
    if(Objects.equals(o1.type, "rrsp")) return -1; 
    else if(Objects.equals(o2.type, "rrsp")) return 1; 
    else if(Objects.equals(o1.type, "tfsa")) return -1; 
    else if(Objects.equals(o2.type, "tfsa")) return 1; 
    else return o1.compareTo(o2); 
}; 
accountTypes.sort(comparator); 

あなたがない場合:AccountTypeComparableを実装して、あなただけの"tfsa""rrsp"の最小値を返しますが、AccountTypeのデフォルトコンパレータにソートの残りの部分を残しComparatorを提供できると仮定すると、

あなたの他のアイテムをソートしたい場合は、常に0を返すデフォルトのコンパレータを用意してください。

+0

これを試してみると、私はこのようなコンパレータを持っていましたが、それはきれいではありません。 – Eefret

+0

ああ、私はrrspとtfsaが必要でしたが、tfsaとrrspがあります。 do – Eefret

+0

はい、私はあなたの質問を誤解しました。編集を参照してください。 – MikaelF

1

ここにはListの文字列を使用して並べ替え順。 sortOrderリストの文字列の順序を変更するだけで、並べ替え順序を変更できます。

Comparator<AccountType> accountTypeComparator = (at1, at2) -> { 
    List<String> sortOrder = Arrays.asList(
     "rrsp", 
     "tfsa", 
     "third" 
     ); 
    int i1 = sortOrder.contains(at1.type) ? sortOrder.indexOf(at1.type) : sortOrder.size(); 
    int i2 = sortOrder.contains(at2.type) ? sortOrder.indexOf(at2.type) : sortOrder.size(); 
    return i1 - i2; 
    }; 
    accountTypes.sort(accountTypeComparator);