我需要通过自己的String属性按自定义顺序(不按字母顺序)对数组列表进行排序。
List<WeekSales> saleList = new ArrayList<>();
...
WeekSales:
public class WeekSales{
private String day;
private int amount;
// getters setters
...
}
属性day
始终是一周中的某一天。 (“星期天”,“星期一”等等......)所以我需要按照一周的顺序订购列表中的元素。(“星期一”,“星期二”,“星期三”,“星期四”,“星期五“,”星期六“,”星期天“)
所以我尝试了google.common.collect.Ordering.
但它给了我一个错误
无法比较值:com.certus.controllers.WeekSales
Comparator<WeekSales> com = Ordering.explicit(new WeekSales("Monday",0), new WeekSales("Tuesday",0), new WeekSales("Wednesday",0), new WeekSales("Thursday",0), new WeekSales("Friday",0), new WeekSales("Saturday",0),new WeekSales("Sunday",0));
saleList.sort(com);
任何帮助都会很明显。谢谢。
更新:
这个question对我的问题没有任何解决方案。在我的情况下,我有一个自定义订单。
("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
答案 0 :(得分:4)
您可以使用地图来提供帮助。
Map<String, Integer> dayToOrder= new HashMap<>();
for (String day: "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday".split(","))
dayToOrder.put(day, dayToOrder.size());
对您的收藏品进行排序
List<WeekSales> saleList = new ArrayList<>();
saleList.sort(Comparator.comparing(ws -> dayToOrder.get(ws.day)));
另一种解决方案是从一开始就使用enum
。
enum WeekDay {
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday;
}
public class WeekSales {
private WeekDay day; // can only be a valid week day
private int amount;
// getters setters
WeekDay getDay() { return day; }
...
}
然后要排序,您可以使用ordinal()
saleList.sort(Comparator.comparing(WeekDay::getDay));
答案 1 :(得分:2)
除非您实际尝试对包含Ordering.explicit
参数中列出的项目的列表进行排序,否则它不知道如何对它们进行排序。如果您覆盖了WeekSales.equals
(以及hashCode
),那也是不明确的,这也是必要的。
您需要实际告诉它要比较的字段:
class YourComparator implements Comparator<WeekSales> {
private final Ordering<String> dayOrdering = Ordering.explicit(
"Monday", "Tuesday", ... );
@Override public int compare(WeekSales a, WeekSales b) {
return dayOrdering.compare(a.getDay(), b.getDay());
}
}
答案 2 :(得分:2)
您是否可以通过以下方式实施比较器:
Comparator<WeekSales> com = new Comparator<WeekSales>() {
@Override
public int compare(WeekSales o1, WeekSales o2) {
//do stuff with o1 and o2 by getDay()
return 0;
}
};
答案 3 :(得分:2)
您可以在工作日使用枚举:
public enum WeekDay {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
然后你的班级会是这样的:
public class WeekSales implements Comparable<WeekSales>{
private WeekDay day;
private int amount;
//Add a comparison method
public int compareTo(WeekSales otherWeekSales) {
return this.day.ordinal() - otherWeekSales.day.ordinal();
}
}
该代码实现了类似的接口,compareTo方法使用WEEKDAY值的顺序进行比较。
并排序:
Collections.sort(saleList); //That will use the compareTo method implemented in the class.