Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala equivalent of new HashSet(Collection)

What is the equivalent Scala constructor (to create an immutable HashSet) to the Java

new HashSet<T>(c)

where c is of type Collection<? extends T>?.

All I can find in the HashSet Object is apply.

like image 587
oxbow_lakes Avatar asked Mar 23 '09 18:03

oxbow_lakes


People also ask

Is Scala set a HashSet?

As per Wikipedia, a Set is a data structure which allows you to store some values but where the values cannot be repeatable. In Scala, a HashSet is a concrete implementation of Set semantics. The HashSet will use the element's hashCode as a key to allow for fast lookup of the element's value within the HashSet.

Is set ordered in Scala?

The default representation of a SortedSet is an ordered binary tree which maintains the invariant that all elements in the left subtree of a node are smaller than all elements in the right subtree. That way, a simple in order traversal can return all tree elements in increasing order. Scala's class immutable.

What does ++ mean in Scala?

The effect of = can also be used to easily understand what ++= would do. Since ++ generally represents concatenation of two collections, ++= would mean an "in place" update of a collection with another collection by concatenating the second collection to the first.

How to add element in HashSet Scala?

Adding an elements in HashSet : We can add an element in HashSet by using + sign. below is the example of adding an element in HashSet. Adding more than one element in HashSet : We can add more than one element in HashSet by using ++ sign.


2 Answers

The most concise way to do this is probably to use the ++ operator:

import scala.collection.immutable.HashSet
val list = List(1,2,3)
val set = HashSet() ++ list
like image 132
Fabian Steeg Avatar answered Sep 19 '22 17:09

Fabian Steeg


There are two parts to the answer. The first part is that Scala variable argument methods that take a T* are a sugaring over methods taking Seq[T]. You tell Scala to treat a Seq[T] as a list of arguments instead of a single argument using "seq : _*".

The second part is converting a Collection[T] to a Seq[T]. There's no general built in way to do in Scala's standard libraries just yet, but one very easy (if not necessarily efficient) way to do it is by calling toArray. Here's a complete example.

scala> val lst : java.util.Collection[String] = new java.util.ArrayList
lst: java.util.Collection[String] = []

scala> lst add "hello"
res0: Boolean = true

scala> lst add "world"
res1: Boolean = true

scala> Set(lst.toArray : _*)
res2: scala.collection.immutable.Set[java.lang.Object] = Set(hello, world)

Note the scala.Predef.Set and scala.collection.immutable.HashSet are synonyms.

like image 40
James Iry Avatar answered Sep 18 '22 17:09

James Iry