我有一个类“SendBundleQuery”,它包含一些对象,如类别,类型,名称。类别可以是两种类型的基础和插件。类型可以是三种类型的数据,语音,短信。我有这个类对象的arraylist,现在我需要排序,就像所有基本优惠将首先和所有插件后。对于所有基本优惠,订单将是数据,语音,短信。
目前我已根据类别
对其进行了分类public int compareTo(SendBundleQuery other) {
int result= category.compareTo(other.category);
if(result==0){
result =other.bundleType.compareTo(bundleType);
}
return result;
}
但现在我需要达到上述条件。什么是做这件事的好方法。
以下是我想要实现的例子。
我需要为客户撰写短信文本,如下所示:
尊敬的客户,
You have <0 MB> left within your <Eenmalig 100 MB Maandbundel>. ---Base offer
In addition, you have <22 Minuten> left within your <100 Minuten Bundel>. --- Base offer
In addition, you have <0 MB> left within your <Web 200 MB Maandbundel>. --Addon
In addition, you have <35 MB> left within your <Alles-in-1 op Reis Data Dagbundel>. --Addon
In addition, you have <374 MB> left within your <Blox 400 MB Maandbundel>. --Addon
In addition, you have <20 Minuten> left within your <Alles-in-1 Op Reis 20 Minuten gesprekken ontvangen>. --Addon
In addition, you have <20 Minuten> left within your <Alles-in-1 Op Reis 20 Minuten Bellen>. --Addon
In addition, you have <20 SMS> left within your <Alles-in-1 Op Reis 20 SMS Dagbundel>. --Addon
这些学分更新至&lt; 12-12-2014&gt;在&lt; 14.53&gt;。
在我的沃达丰中维护您的BloX和额外内容。
下面是当前的结果,但顺序就像数据,短信,然后是语音,但我需要数据,语音,然后是短信:
Dear Customer,
You have 0.0 MB Data left within your Web 500 MB Maandbundel.
In addition, you have 106 minutes left within your 150 Minuten Bundel.
In addition, you have 35.0 MB Data left within your Alles-in-1 op Reis Data Dagbundel.
In addition, you have 20 messages left within your Alles-in-1 Op Reis 20 SMS Dagbundel.
In addition, you have 20 minutes left within your Alles-in-1 Op Reis 20 Minuten gesprekken ontvangen.
In addition, you have 20 minutes left within your Alles-in-1 Op Reis 20 Minuten Bellen.
These credits are updated until 15-12-2014 at 03:57.
Maintain your BloX and extras in My Vodafone.
答案 0 :(得分:2)
要按多个条件排序,请按以下方式编写compareTo
:
public int compareTo(SendBundleQuery other) {
int result = category1.compareTo(other.category1);
if( result == 0 ) {
result = category2.compareTo(other.category2);
}
return result;
}
答案 1 :(得分:2)
如果您要检查多个条件,请按重要性顺序检查它们。每当比较结果为0时(即,在条件相同时),继续检查下一个。
一个空的例子,因为我没有足够的信息根据您的帖子为您提供确切的代码:
public int compareTo(SomeObject other) {
int comparison1 = someProperty.compareTo(other.someProperty);
if( comparison1 != 0 ) {
return comparison1; // the highest priority ordening is leading
}
int comparison2 = someLessImportantProperty.compareTo(other.someLessImportantProperty);
if( comparison2 != 0 ) {
return comparison2; // the second highest priority ordening is leading
}
// if neither of the more important ones matter; sort by the least important one
return someUnImportantProperty.compareTo(other.someUnImportantProperty);
}
答案 2 :(得分:1)
由于Java 8方法引用和lambda为常见的排序要求添加了一组额外的优雅方法。其中之一就是您所需要的:首先根据属性x进行排序,如果不可用,则根据属性y进行排序。
humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
(完整示例here)。
这将基于两个getter方法对Human
个对象的列表进行排序。
对于您而言,Human
为SendBundleQuery
,而获取者就是您需要排序的内容。