Best way to list files in Java, sorted by Date Modified?

后端 未结 17 893
-上瘾入骨i
-上瘾入骨i 2020-11-22 11:51

I want to get a list of files in a directory, but I want to sort it such that the oldest files are first. My solution was to call File.listFiles and just resort the list ba

17条回答
  •  有刺的猬
    2020-11-22 12:34

    There is also a completely different way which may be even easier, as we do not deal with large numbers.

    Instead of sorting the whole array after you retrieved all filenames and lastModified dates, you can just insert every single filename just after you retrieved it at the right position of the list.

    You can do it like this:

    list.add(1, object1)
    list.add(2, object3)
    list.add(2, object2)
    

    After you add object2 to position 2, it will move object3 to position 3.

提交回复
热议问题