最近一次的日值列表 [英] Nearest time-of-day value in List
问题描述
有没有什么办法来显示一个列表(或任何其他可能做类似的功能)的元素比较当前时间。
所以,我提出了包含时间一个ArrayList,不具有重复任何模式进行,使用的方法,以增加它为10分钟(例如)不会对
Is there any way to display element of a list (or any other that might do similar function) comparing to current time. So, I made an arraylist that contains time, which doesn't have any pattern of repetition, using method to increase it for 10 min (for instance) won't to.
我有以下几点:
日期函数,它具有当前时间:
Date function that has current time:
Date date = new Date();
DateFormat dateformat = new SimpleDateFormat("HH:mm:ss");
ArrayList中有时间,我需要:
ArrayList that has time that I need:
ArrayList<String> time = new ArrayList<String>();
time.add("5:40");
time.add("6:40");
time.add("8:30");
time.add("9:45");
time.add("10:35");
time.add("11:10");
time.add("11:55");
time.add("12:20");
time.add("13:30");
time.add("14:55");
time.add("16:00");
time.add("16:30");
time.add("17:30");
time.add("19:00");
time.add("20:10");
time.add("21:10");
现在我很好奇,也因为我是新来这个,有没有办法做下一个:
Now I'm curious, and also because I'm new to this, is there a way to do next:
1)考虑到会有很多,将有一次阵的,有没有办法(也许还包括一些code的例子)写一个方法,将有一个参数,所以用户可以选择时间,他们要显示它?
1) Considering there will be a lot of arrays that will have time, is there a way (perhaps with some code examples) to write a method that will have an argument so user can choose which 'time' they want it to be displayed?
2)会不会有需要使用循环一次(在这种情况下,'时间'数组)到达终点,还是可以这么写它根据当前时间自动进入开始。
2) Will there be need to use loop once (in this case 'time' array) it reaches the end, or can it be written so it automatically goes to beginning based on current time.
3) code优化:可以对此进行了更实际的方式被写入
3) Code optimisation: can this be written in more practical way?
我是相当新的这一点,所以任何帮助(指导和code的例子)是多少AP preciated这样我就可以在这个项目中,并作为学习材料将来的使用。
I am fairly new to this, so any help (with guidance and code examples) is much appreciated so I can use it in this project and as learning material for future ones.
推荐答案
就像@BasilBourque,我建议存放倍LocalTimes - 但我也建议使用的 NavigableSet
如的 TreeSet的
代替//docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html nofollow的一个列表
(我假设在你的列表中的时间均是唯一的)。
Like @BasilBourque, I suggest storing the times as LocalTimes - but I would also suggest using a NavigableSet
such as TreeSet
instead of a List
(I'm assuming that the times in your list are all unique).
的想法是, TreeSet的
拥有的在上限
方法,它不正是你所需要的:
The idea is that TreeSet
has a ceiling
method that does exactly what you need:
返回此的最小元素设置为大于或等于给定元件,或空;如果不存在这样的元素
Returns the least element in this set greater than or equal to the given element, or null if there is no such element.
您可以接着写:
TreeSet<LocalTime> times = new TreeSet<> ();
times.add(LocalTime.parse("05:40"));
times.add(LocalTime.parse("06:40"));
times.add(LocalTime.parse("08:30"));
//...
LocalTime ceiling = times.ceiling(LocalTime.now());
if (ceiling != null) //do something with it
这篇关于最近一次的日值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!