我写了这段代码
final List<Future<?>> list = _scheduledTasks.remove(clazz);
if (Objects.nonNull(list))
{
list.stream().filter(Objects::nonNull).forEach(s -> s.cancel(true));
}我怎样用java 8风格把它写成一行?
发布于 2020-08-28 20:34:40
在Java 9+中,像这样使用Optional:
Optional.ofNullable(_scheduledTasks.remove(clazz))
.stream() // Added in java 9
.flatMap(List::stream)
.filter(Objects::nonNull)
.forEach(s -> s.cancel(true));
// As "1 line"
Optional.ofNullable(_scheduledTasks.remove(clazz)).stream().flatMap(List::stream).filter(Objects::nonNull).forEach(s -> s.cancel(true));在Java8中,使用ifPresent()。有点不那么优雅。
Optional.ofNullable(_scheduledTasks.remove(clazz))
.ifPresent(x -> x.stream()
.filter(Objects::nonNull)
.forEach(s -> s.cancel(true)));
// As "1 line"
Optional.ofNullable(_scheduledTasks.remove(clazz)).ifPresent(x -> x.stream().filter(Objects::nonNull).forEach(s -> s.cancel(true)));https://stackoverflow.com/questions/63633777
复制相似问题