I'm new to Scala, and I'm addicted to mixing Java and Scala Lists. I think that people who usually write Java and are new to Scala may be addicted to it, so I will share the cause and solution.
I want to extract only the necessary information from the list of tweets returned by the API of Twitter4J (ResponseList [Status]) and get a List of my own class Tweet type. In Java, if you use Stream API, you can kill it instantly.
The ResponseList returned from the Twitter4J API can use the Stream API, so it looks like this when written in Java style.
val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
val tweets: List[Tweet] = statuses
.stream()
.map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
.collect(Collectors.toList) //For some reason there is a compile error here ...
The Stream API termination operation .collect (Collectors.toList)
returns java.util.List, but the type of the variable to be stored is Scala List type.
Scala can use both Scala API and Java API, but they are different. Both offer types with the same name, but don't mix them up.
The easiest.
val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
val tweets: java.util.List[Tweet] = statuses
.stream()
.map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
.collect(Collectors.toList)
However, if the method returns the variable tweets, Scala's List is good! Because it's Scala.
According to the Scala documentation (https://docs.scala-lang.org/en/overviews/collections/conversions-between-java-and-scala-collections.html), Scala and Java collections are converted to each other. It seems that it can be done.
//JavaConverters class is responsible for converting collections
import scala.collection.JavaConverters._
val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
val tweets: List[Tweet] = statuses
//ResponseList(Java) => mutable.Buffer(Scala)
.asScala
//Then use the Scala collection operation API
.map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
.toList
Scala | Java |
---|---|
Iterator | java.util.Iterator |
Iterator | java.util.Enumeration |
Iterable | java.lang.Iterable |
Iterable | java.util.Collection |
mutable.Buffer | java.util.List |
mutable.Set | java.util.Set |
mutable.Map | java.util.Map |
mutable.ConcurrentMap | java.util.concurrent.ConcurrentMap |
It is possible to convert by declaring ʻimport collection.JavaConverters._ and then using ʻasJava
method and ʻasScala` method. However, it seems that it is not all-purpose, so please use it with care. For more information, see Official Documentation
Convert collections between Scala Documentation JAVA and SCALA
Recommended Posts