如何将 Java Stream 的 collect 转换为 Scala。

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

How to convert java stream collect to scala

问题

Scala代码

objRefs = objRefs.filter(objRef => DataUtil.isNotEmpty(objRef)).to(LazyList)

以下代码会编译错误

objRefs = objRefs.filter(objRef => DataUtil.isNotEmpty(objRef)).to(LazyList)
英文:

Java code

objRefs = objRefs.stream().filter(objRef -> DataUtil.isNotEmpty(objRef)).collect(Collectors.toCollection(LinkedHashSet::new));

How to convert it to scala?
Following code compile error

objRefs = objRefs.stream().filter(objRef => DataUtil.isNotEmpty(objRef)).collect(Collectors.toCollection(LinkedHashSet::new));

答案1

得分: 2

LinkedHashSet::new 不是有效的 Scala 代码。你是不是想调用 LinkedHashSet 的构造函数?如果是的话,可以使用 new LinkedHashSet(_)

你选择的解决方案是将 Java 转译为 Scala。如果这样做,使用 Scala 的价值就很小了,还不如直接使用 Java。

一个更符合惯用法的解决方案是

objRefs.stream().filter(DataUtil.isNotEmpty).asScala(Set)

英文:

LinkedHashSet::new is not valid scala. Do you mean to call the constructor of LinkedHashSet? If so, use new LinkedHashSet(_)

The solution you've chosen is translating java to scala. If you do that, there is little value in using scala at all, and you might as well use java.

A more idiomatic solution would be

objRefs.stream().filter(DataUtil.isNotEmpty).asScala(Set)

huangapple
  • 本文由 发表于 2020年9月11日 17:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63844823.html
匿名

发表评论

匿名网友

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

确定