java 如何在Java中获取List的最早日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39791318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:38:36  来源:igfitidea点击:

How to get the earliest date of a List in Java?

javadatecompare

提问by mffm

I have an ArrayList which stores 0...4 Dates.

我有一个存储 0...4 个日期的 ArrayList。

The amount of Dates in the list depends on a Business logic.

列表中的日期数量取决于业务逻辑。

How can I get the earliest date of this list? Of course I can build iterative loops to finally retrieve the earliest date. But is there a 'cleaner'/ quicker way of doing this, especially when considering that this list can grow on a later perspective?

我怎样才能得到这个列表的最早日期?当然,我可以构建迭代循环来最终检索最早的日期。但是有没有一种“更干净”/更快的方法来做到这一点,尤其是考虑到这个列表可以在以后的角度增长时?

回答by Andy Turner

java.util.Dateimplements Comparable<Date>, so you can simply use:

java.util.Date实现Comparable<Date>,所以你可以简单地使用:

Date minDate = Collections.min(listOfDates);

This relies on there being at least one element in the list.

这依赖于列表中至少有一个元素。

回答by ΦXoc? ? Пepeúpa ツ

If you dont mind to change the insertion order then sort the list and get the elemeent at index 0

如果您不介意更改插入顺序,则对列表进行排序并在索引 0 处获取元素

回答by JF Meier

SortedSet

SortedSet

Depending on your application you can think about using a SortedSet(like TreeSet). This allows you to change the collection and always receive the lowest element easily.

根据您的应用程序,您可以考虑使用SortedSet(如TreeSet)。这允许您更改集合并始终轻松接收最低元素。

Adding elements to the collection is more expensive, though.

但是,向集合中添加元素的成本更高。