英文:
Converting from scala.collection.immutable.List to a java.util.List in java
问题
I’m currently working within a java runtime google cloud dataflow. The scala sdk I'm using shows the property I'm working with as an immutable list: https://github.com/snowplow/snowplow-scala-analytics-sdk/blob/master/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/Event.scala#L91
final List<SelfDescribingData
Does anyone have any pointers on how to properly cast / convert this to a Java list? Most of the examples I have found are doing this in the Scala runtime vs the Java runtime.
I had thought the JavaConverters package would help me here, however these methods don't seem to be expecting an immutable scala list.
Where e in the example below is an instance of the Event in the linked sdk.
List<SelfDescribingData
for (SelfDescribingData
LOG.info(t.toString());
}
英文:
I’m currently working within a java runtime google cloud dataflow. The scala sdk I'm using shows the property I'm working with as an immutable list: https://github.com/snowplow/snowplow-scala-analytics-sdk/blob/master/src/main/scala/com.snowplowanalytics.snowplow.analytics.scalasdk/Event.scala#L91
final List<SelfDescribingData<Json>> contexts
Does anyone have any pointers on how to properly cast / convert this to a Java list? Most of the examples I have found are doing this in the Scala runtime vs the Java runtime.
I had thought the JavaConverters package would help me here, however these methods don't seem to be expecting an immutable scala list.
Where e in the example below is an instance of the Event in the linked sdk.
List<SelfDescribingData<Json>> list = JavaConverters.asScalaBufferConverter(e.contexts()).asScala().toList();
for (SelfDescribingData<Json> t : list) {
LOG.info(t.toString());
}
答案1
得分: 3
JavaConverters.asScalaBufferConverter
:
> 添加一个名为 asScala
的方法,隐式地将 Java List 转换为 Scala mutable Buffer
要将 scala.collection.immutable.List
(它是 scala.collection.immutable.Seq
和 scala.collection.Seq
的子类型)转换为 java.util.List
,您可以调用 JavaConverters.asJava
:
java.util.List<SelfDescribingData<Json>> list = JavaConverters.asJava(e.contexts().data())
我发布的代码是在 Scala 2.13 集合重写之后的版本。对于较早版本的 Scala,等效函数是 JavaConverters.seqAsJavaList
。
英文:
JavaConverters.asScalaBufferConverter
:
> Adds an asScala method that implicitly converts a Java List to a Scala mutable Buffer
To convert a scala.collection.immutable.List
, which is a subtype of scala.collection.immutable.Seq
and scala.collection.Seq
to a java.util.List
you would call JavaConverters.asJava
:
java.util.List<SelfDescribingData<Json>> list = JavaConverters.asJava(e.contexts().data())
The code I've posted is after the Scala 2.13 collection rewrite. For older versions of Scala, the equivalent function is JavaConverters.seqAsJavaList
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论