用部分显式排序,然后再用另一种顺序? [英] Ordering with partial explicit and then another order?

查看:72
本文介绍了用部分显式排序,然后再用另一种顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以自定义方式订购列表,我正在寻找正确的方法,并找到了番石榴的Ordering api,但事实是,我订购的列表并不总是相同,并且我只需要2个字段位于列表的顶部,例如,我有这个字段:

What I need is to order a list in a custom way, I'm looking into the correct way and found guava's Ordering api but the thing is that the list I'm ordering is not always going to be the same, and I just need 2 fields to be at the top of the list, for example I have this:

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

我尝试使用自定义比较器并在Guava库中使用Ordering,如下所示:

I tried with a custom comparator and using Ordering in Guava library, something like this:

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

但这会引发异常,因为显式排序不支持其他您提供的列表中没有的项目,是否可以进行部分显式排序?

but it throws an exception because explicit ordering doesnt support other items that are not in the list you provided, is there a way to do a partial explicit ordering? something like:

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


推荐答案

为此,您不需要番石榴

假设 AccountType 实现可比较,您只需提供一个比较器即可返回 tfsa 的最小值 rrsp ,但是将其余排序留给 AccountType 的默认比较器:

Assuming AccountType implements Comparable, you can just provide a Comparator that returns minimum values for "tfsa" and "rrsp", but leaves the rest of the sorting to AccountType's default comparator:

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。

If you don't want your other items sorted, just provide a default comparator that always returns 0.

这篇关于用部分显式排序,然后再用另一种顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆