3 回答
TA贡献1794条经验 获得超8个赞
您可以尝试查看列表的两端,对索引进行计数,直到找到在所需开始时间之后或等于所需开始时间的第一个索引,同时向后迭代以获取您要查找的时间段中最后一次的索引。就像是:
int first;
for (LocalDateTime time : timeStampList){
if (time.compareTo(startTime) < 0){
first++;
}else{
return i + 1;
}
}
int last = list.length();
while (last > 0){
LocalDateTime time = timeStampList[last];
if (time.compareTo(endTime) > 0){
last -= 1;
}else{
return last - 1;
}
}
然后,您要查找的子集将是这些索引之间的所有内容(包括)
TA贡献1982条经验 获得超2个赞
您可以使用subSet方法NavigableSet
NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
它可能是这样的:
NavigableSet<LocalDateTime> treeSet = new TreeSet<>(yourListWithTimestamps);
//Initialize your start and end date-times:
LocalDateTime start = LocalDateTime.parse("2019-03-01T10:10:10");
LocalDateTime end = LocalDateTime.parse("2019-03-01T22:22:21");
NavigableSet<LocalDateTime> subSet = treeSet.subSet(start, false, end, false);
//Optional - convert it back to list:
List<LocalDateTime> subList = new ArrayList<>(subSet);
TA贡献1815条经验 获得超6个赞
我可以向您推荐以下完全不使用 drop 的代码:
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SublistWithLambda {
public static void main(String[] args) {
List<LocalDateTime> dates = Arrays.asList(
LocalDateTime.now().minusHours(24),
LocalDateTime.now().minusHours(22),
LocalDateTime.now().minusHours(20),
LocalDateTime.now().minusHours(12),
LocalDateTime.now().minusHours(10),
LocalDateTime.now().minusHours(7),
LocalDateTime.now().minusHours(5)
);
BiPredicate<LocalDateTime, LocalDateTime> isLessThan12Hours = (date1, date2) -> {
Duration duration = Duration.between(date2, date1);
return duration.toHours() >= 0 && duration.toHours() <= 12;
};
List<List<LocalDateTime>> result = IntStream
.range(0, dates.size())
.mapToObj(i -> dates.stream().skip(i)
.takeWhile(date -> isLessThan12Hours.test(date, dates.get(i)))
.collect(Collectors.toList()))
.collect(Collectors.toList());
result.forEach(System.out::println);
}
}
我希望这就是你要找的。
添加回答
举报