I need to write a code that compares performance of Java's ArrayList
with Scala's List
. I am having a hard time getting the Scala List
working in my Java code. Can some one post a real simple "hello world" example of how to create a Scala List
in java code (in a .java
file) and add say 100 random numbers to it?
PS: I am quite good at Java but have never used Scala.
Specific to Scala, a list is a collection which contains immutable data, which means that once the list is created, then it can not be altered. In Scala, the list represents a linked list. In a Scala list, each element need not be of the same data type.
In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.
Because a List is immutable, if you need to create a list that is constantly changing, the preferred approach is to use a ListBuffer while the list is being modified, then convert it to a List when a List is needed. The ListBuffer Scaladoc states that a ListBuffer is “a Buffer implementation backed by a list.
Use scala.collection.JavaConversions from inside of java.
For example to create a nested scala case class that requires a scala List in its constructor:
case class CardDrawn(player: Long, card: Int)
case class CardSet(cards: List[CardDrawn])
From Java you can use asScalaBuffer(x).toList() as follows:
import scala.collection.JavaConversions;
import java.util.ArrayList;
import java.util.List;
public CardSet buildCardSet(Set<Widget> widgets) {
List<CardDrawn> cardObjects = new ArrayList<>();
for( Widget t : widgets ) {
CardDrawn cd = new CardDrawn(t.player, t.card);
cardObjects.add(cd);
}
CardSet cs = new CardSet(JavaConversions.asScalaBuffer(cardObjects).toList());
return cs;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With