Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an Array[String] to a Set[String]?

I have an array of strings. What's the best way to turn it into an immutable set of strings?

I presume this is a single method call, but I can't find it in the scala docs.

I'm using scala 2.8.1.

like image 429
dave4420 Avatar asked Apr 25 '11 13:04

dave4420


People also ask

Can I convert an array to Set in Java?

Converting an array to Set objectThe Arrays class of the java. util package provides a method known as asList(). This method accepts an array as an argument and, returns a List object. Use this method to convert an array to Set.

Can we convert string [] to string?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.


2 Answers

This method called toSet, e.g.:

scala> val arr = Array("a", "b", "c") arr: Array[java.lang.String] = Array(a, b, c)  scala> arr.toSet res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c) 

In this case toSet method does not exist for the Array. But there is an implicit conversion to ArrayOps.

In such cases I can advise you to look in Predef. Normally you should find some suitable implicit conversion there. genericArrayOps would be used in this case. genericWrapArray also can be used, but it has lower priority.

like image 183
tenshi Avatar answered Sep 25 '22 17:09

tenshi


scala> val a = Array("a", "b", "c") a: Array[java.lang.String] = Array(a, b, c)  scala> Set(a: _*) res0: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c)  // OR      scala> a.toSet res1: scala.collection.immutable.Set[java.lang.String] = Set(a, b, c) 
like image 32
missingfaktor Avatar answered Sep 22 '22 17:09

missingfaktor