我目前正在编写一个显示值的Java程序,AreaChart并且这样做我有一个ArrayList,其名称dataList来自泛型类型AreaChartPair.
每个都AreaChartPair包含X轴(字符串)值和Y轴(整数)值.
X轴是日期,Y轴是计数器,因为所有数据都是从文件中读取的,所以日期将按未排序的顺序排列.要对它们进行排序我使用此功能:
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
这并没有完全解决我的问题,因为它只会比较前几个字母数字字符(即02.09.2030后来01.01.2000,因为02之后01)
为了解决这个问题,我简单地将日期反转dd.mm.yyyy为yyyy.mm.dd,使用上面的函数对列表进行排序,然后将字符串反转回dd.mm.yyyy
我现在的问题是如何简化这段代码,因为它是重复的:
//replaces the current data with the reversed string
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
//sorts the data
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue));
//reverses the string back to normal, so it can be displayed
for (int index = 0; index < dataList.size(); index++) {
dataList.set(index, new AreaChartPair(model.reverseDate(dataList.get(index).getXAxisStringValue()),
dataList.get(index).getYAxisIntegerValue()));
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
执行排序的较短方法是即时进行倒车.该字符串也可以解析为实际日期对象,以使其更清晰,但这需要catch块和dateformatter对象,所以我不会在这里编写该代码.
dataList.sort(Comparator.comparing(AreaChartPair::getXAxisStringValue,
(a, b) -> {
return model.reverseDate(a).compareTo(model.reverseDate(b));
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
351 次 |
| 最近记录: |