Collections.singletonList使用lambda表达式

huangapple go评论125阅读模式
英文:

Collections.singletonList with lambda expressions

问题

  1. 我有这段代码目前可以正常运行
  2. 返回获取Hostimeta的时间getHostimeta(time)):
  3. .stream() // 转换为流
  4. .filter(e -> e.getPersonneId() == enfantId) // 过滤条件,筛选符合条件的元素
  5. .collect(Collectors.toList()) // 将流中的元素收集到列表中
  6. .get(0); // 获取列表中的第一个元素
  7. 我想要验证列表是否只有一个元素
  8. 返回Collections.singletonList(...)其中包含
  9. .stream() // 转换为流
  10. .filter(e -> e.getPersonneId() == enfantId) // 过滤条件,筛选符合条件的元素
  11. .collect(Collectors.toList()) // 将流中的元素收集到列表中
  12. 但是我遇到了以下编译错误
  13. 所需类型
  14. IHostimeta
  15. 提供类型
  16. List<Hostimeta>
英文:

I have this piece of code that is working fine:

  1. return getHostimeta(time)
  2. .stream()
  3. .filter(e -&gt; e.getPersonneId() == enfantId)
  4. .collect(Collectors.toList()).get(0);

I want to verify that the list has only 1 element:

  1. return Collections.singletonList(getHostimeta(time)
  2. .stream()
  3. .filter(e -&gt; e.getPersonneId() == enfantId)
  4. .collect(Collectors.toList())).get(0);

but I have this compilation error:

  1. Required type:
  2. IHostimeta
  3. Provided:
  4. List&lt;Hostimeta&gt;

答案1

得分: 0

Collections.singletonList()在解决这个问题时毫无帮助。最可行的解决方案有:

  • collect(toList())的结果存储在一个变量中,在另一行中检查其大小是否为1。
  • 使用另一个收集器——可以是自己编写的,也可以使用第三方库中的现有收集器,因为Java本身没有提供任何真正有助于此问题的解决方案。
  • 通过其他集合操作来实现,例如:
  1. stream.reduce((a, b) -> { throw new IllegalStateException(); }).get()
英文:

Collections.singletonList() will not help you in any way with this problem. The most plausible available solutions are

  • to store the result of collect(toList()) in a variable and, on a separate line, check that its size is 1

  • to use another collector -- either inventing your own, or using an existing one from a third party library, since Java doesn't provide anything that can really help here out of he box

  • to make this out of other collection operations, e.g.

    1. stream.reduce((a, b) -&gt; { throw new IllegalStateException(); }).get()

huangapple
  • 本文由 发表于 2020年10月18日 01:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64405169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定