【问题标题】:Why doesn't stream() work in Scala the way it does in Java? Is there any other API that does the same as stream() API?为什么 stream() 在 Scala 中不像在 Java 中那样工作?是否有任何其他 API 与 stream() API 相同?
【发布时间】:2019-06-30 19:19:36
【问题描述】:

尝试在 Scala 中运行以下代码。它返回一个“缺少参数类型”错误。

def printTree(e: Element, depth: Int){
    System.out.println("Number of children in element : ",e.getChildren().getClass());
    System.out.println(StringUtils.repeat("\t", depth) + e.getText());
    e.getChildren().stream().filter(c=>c instanceOf Element).foreach(c=>printTree((Element)c, depth+1));
}

【问题讨论】:

  • Element 是什么(完全限定名?),这与 spark 有什么关系?
  • 一般来说,.stream() 会将 scala 集合转换为 Stream,这是一种特殊的惰性数据结构
  • c instanceOf Element(Element)c 不是有效的 Scala。
  • @AlexeyRomanov 是的,我将其更改为c instanceOf[Type],但它不起作用。
  • c.isInstanceOf[Element]c.asInstanceOf[Element]

标签: java scala java-8 functional-programming java-stream


【解决方案1】:

在 Scala 中,您不需要显式地使用 Java 流。如果e.getCgildren() 返回Array,则可以省略.stream(),其余部分将编译。

【讨论】:

  • 感谢您回复@Andronicus。 e.getChildren() 是类 org.jdom.ContentList$FilterList 类类型而不是数组
  • 修复了这个问题:e.getChildren().filter(c=>c.isInstanceOf[Element]).foreach(c=>printTree(c.asInstanceOf[Element], depth+1))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2017-08-24
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多