2017-02-08 25 views
1

我需要的是以自定义的方式排列列表,我正在研究正确的方法,并找到番石榴的排序API,但事情是,我订购的列表并不总是相同的,我只需要2场是在列表的顶部,例如我有这样的:使用部分显式和其他顺序排序?

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 

我试图用一个自定义的比较,并使用排序,番石榴库中,这样的事情:

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

但它会抛出一个异常,因为显式排序不支持不在你提供的列表中的其他项目,有没有办法做一个部分显式的o订货信?像这样:

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

如果你刚在'AccountType'属性('order' /'priority'),这将是'1'和'2'这两个帐户类型和'0'每一个其他类型的?然后你会定义主要基于该属性的顺序。 –

+0

[Guava:如何从列表和单个元素创建明确的排序?]可能的副本(http://stackoverflow.com/questions/14403114/guava-how-to-create-an-explicit-ordering-from -a-list-and-a-single-element) –

回答

1

你不需要番石榴为此,你需要的一切都在收集API。

假设AccountType实现Comparable,你可以提供一个Comparator,用于返回"tfsa""rrsp"最低值,但保留分拣到AccountType的默认比较器的其余部分:

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

如果你不这样做希望您的其他物品排序,只是提供总是返回0的默认比较。

+0

将尝试这一个,我有一个比较器,但这不是那么干净 – Eefret

+0

哦,我需要rrsp,然后tfsa,但得到tfsa然后rrsp,我想改变的价值将做 – Eefret

+0

是的,我误解了你的问题。请参阅编辑。 – MikaelF

1

这是一个Comparator解决方案,它使用字符串的List表示yo你的排序顺序。只需更改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);