按日期排序路径 - 实用程序方法

时间:2013-04-15 04:11:48

标签: java sorting path

在某些包中是否有任何实用程序类,如commons-io,jodatime等,其中一个可以传入如下列表:

March/Invoice - 00000020 - 01.03.2013.xls
March/Invoice - 00000021 - 08.03.2013.xls
April/Invoice - 00000025 - 05.04.2013.xls
January/Invoice - 00000015 - 25.01.2013.xls

并按月分类路径:

January/Invoice - 00000015 - 25.01.2013.xls
March/Invoice - 00000020 - 01.03.2013.xls
March/Invoice - 00000021 - 08.03.2013.xls
April/Invoice - 00000025 - 05.04.2013.xls

我们可能自己编写一个Comparator,但我希望某些第三方库中已存在这样的东西?

1 个答案:

答案 0 :(得分:1)

这样的事情比搜索任何第三方图书馆更好,我相信:

final Map<String, Integer> monthMap = new LinkedHashMap<String, Integer>();
// Initialize it with all the months and corresponding index like:
// (January,1), (February,2), etc...
monthMap.put("January", 1);
monthMap.put("February", 2);
monthMap.put("March", 3);
monthMap.put("April", 4);
monthMap.put("May", 5);
monthMap.put("June", 6);
monthMap.put("July", 7);
monthMap.put("August", 8);
monthMap.put("September", 9);
monthMap.put("October", 10);
monthMap.put("November", 11);
monthMap.put("December", 12);

Collections.sort(list, new Comparator<String>()
{
    @Override
    public int compare(String a, String b)
    {
        String first = a.substring(0, a.indexOf(File.separatorChar));
        String second = b.substring(0, b.indexOf(File.separatorChar));

        return monthMap.get(first).compareTo(monthMap.get(second));
    }
});

我相信可以有一个更好的解决方案,它只是一个指针。