Frage

I have java API which returns java.util.set, I want to iterate over the set till the size-1 and create new java.util.hashset in scala

I tried following :

val keys = CalltoJavaAPI()
val newHashSet = new java.util.HashSet()
val size = keys.size();
newHashSet.add(keys.take(keys.size() - 1))

But I am getting following error:

Caused by: java.lang.UnsupportedOperationException
    at java.util.AbstractCollection.add(AbstractCollection.java:221)

Tried Following but still not working

    val keys = CalltoJavaAPI().asScala        
    var newHashSet = new scala.collection.mutable.HashSet[Any]()
    newHashSet.add(keys.take(keys.size - 1))
War es hilfreich?

Lösung

Use scala.collection.JavaConversions for implicit conversions between Scala and Java collections.

In the following approach we convert a Java HashSet onto a Scala Set, extract keys of interest, and convert the result onto a new Java HashSet:

import scala.collection.JavaConversions._

val javaKeys = new java.util.HashSet[Any](CalltoJavaAPI()) 
val n = javaKeys.size 

val scalaSet = javaKeys.toSet.take(n-1)

val newJavaHashSet = new java.util.HashSet[Any]()
newJavaHashSet.addAll(scalaSet)

Andere Tipps

I think you should use newHashSet.addAll(...) instead of newHashSet.add(...) since keys.take(...) returns a List.

From the docs:

public boolean add(E e): Adds the specified element to this set if it is not already present.

public boolean addAll(Collection c): Adds all of the elements in the specified collection to this collection

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top