Java 如何从选项集合中获取数据?

Java 如何从选项集合中获取数据?,java,collections,java-8,java-stream,optional,Java,Collections,Java 8,Java Stream,Optional,我有一种返回产品集合的方法: Collection<Product> getProducts() { ... } Collection getProducts(){…} 每种产品都有保证书。但这不是必须的 interface Product { Optional<Guarantee> getGuarantee(); } 接口产品{ 可选的getGuarrance(); } 现在我需要检查一下所有的产品,看看保证书是否过期了。未过期的应收集到列表中 我就

我有一种返回产品集合的方法:

Collection<Product> getProducts() { ... }  
Collection getProducts(){…}
每种产品都有保证书。但这不是必须的

interface Product {
    Optional<Guarantee> getGuarantee();
}
接口产品{
可选的getGuarrance();
}
现在我需要检查一下所有的产品,看看保证书是否过期了。未过期的应收集到列表中

我就是这么做的:

List<Optional<Guarantee>> optionalGar = getProducts().stream()
      .map(f -> f.getGuarantee()).collect(Collectors.toList());

List<Guarantee> gar = optionalGar.stream()    
      .map(op -> op.orElse(null))             
      .filter(Objects::nonNull)
      .filter(g -> !g.hasExpired())
      .collect(Collectors.toList());
List optionalGar=getProducts().stream()
.map(f->f.getGuarrance()).collect(Collectors.toList());
List gar=optionalGar.stream()
.map(op->op.orElse(空))
.filter(对象::非空)
.filter(g->!g.hasExpired())
.collect(Collectors.toList());
有没有办法避免使用
.orElse(null)

(将其替换为
op.get()
将在可选项为空时导致异常)


附言:我可以在Java8和Java9之间自由选择,因此欢迎使用这两种解决方案(不确定两者是否不同)

Java8

List<Guarantee> expiredGuarantees = getProducts().stream()
                                                 .map(Product::getGuarantee)    
                                                 .filter(Optional::isPresent)
                                                 .map(Optional::get)
                                                 .filter(not(Guarantee::hasExpired))
                                                 .collect(toList());
注意

Java8没有
谓词。没有
方法。仅从第11版开始包含

通过向项目中添加以下方法,您将能够将其与上述解决方案一起使用

public static <T> Predicate<T> not(Predicate<T> predicate) { 
    return predicate.negate();
}
公共静态谓词not(谓词谓词){
返回谓词.negate();
}
更新

虽然这不是社区,但以下是关于您的代码的一些注释:

  • 通过将两个管道组合成一个管道,您的代码将更干净(在这种特殊情况下)
  • 如果可能,首选
    方法参考
    而不是
    lambda
  • 为变量指定适当的名称,以便使代码更易于维护
public static <T> Predicate<T> not(Predicate<T> predicate) { 
    return predicate.negate();
}