0

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))
2
  • have you tried anything yet? thats the only way we can helpt you ;) Commented Feb 3, 2014 at 14:25
  • Are you sure the exception is thrown on that line? As you can see from the source (and also from your exception) the UnsupportedOperationException is thrown from AbstractCollection, which is impossible if you call .add(Object) on a HashSet, because it overrides the behavior (see the source). Commented Feb 3, 2014 at 14:55

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.