Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use scala.collection.immutable.List in a Java code

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.

like image 202
Shaunak Avatar asked Jul 05 '11 06:07

Shaunak


People also ask

Is Scala list immutable?

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.

How do you make a Java collection immutable?

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.

How do I create a mutable list in Scala?

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.


1 Answers

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;
}
like image 72
simbo1905 Avatar answered Oct 25 '22 19:10

simbo1905