Java Collections.singletonList与lambda表达式

Java Collections.singletonList与lambda表达式,java,lambda,collections,java-8,functional-programming,Java,Lambda,Collections,Java 8,Functional Programming,我有一段代码运行良好: return getHostimeta(time) .stream() .filter(e -> e.getPersonneId() == enfantId) .collect(Collectors.toList()).get(0); 我要验证列表是否只有1个元素: return Collections.single

我有一段代码运行良好:

   return getHostimeta(time)
                        .stream()
                        .filter(e -> e.getPersonneId() == enfantId)
                        .collect(Collectors.toList()).get(0);
我要验证列表是否只有1个元素:

return Collections.singletonList(getHostimeta(time)
        .stream()
        .filter(e -> e.getPersonneId() == enfantId)
        .collect(Collectors.toList())).get(0);
但我有一个编译错误:

Required type:
IHostimeta

Provided:
List<Hostimeta>
所需类型:
伊霍斯蒂梅塔
提供:
列表

集合。singletonList()
不会以任何方式帮助您解决此问题。最可行的解决方案是

  • 要将
    collect(toList())
    的结果存储在变量中,并在单独的行上检查其大小是否为1

  • 使用另一个收集器——要么发明自己的收集器,要么使用,因为Java并没有提供任何真正有用的东西

  • 要使其脱离其他收集操作,例如

    stream.reduce((a, b) -> { throw new IllegalStateException(); }).get()
    
Collections.singletonList无法验证这一点。您可以检查列表的大小。和Collections.singletonList不接受列表,它接受一个元素并创建该元素的列表。所以,当前它返回列表,然后get(0)表示您正在返回列表。通常,您应该阅读并了解它的用途,而不是进行猜测。