Java collections to Scala: what's the best way to convert java.util.list to scala.immutable.Set?

StackOverflow https://stackoverflow.com/questions/21210448

Frage

I need to get a Scala immutable Set from a java.util.List in order to take advantage of the constraint that Set class has about the unicity of its elements (I expect to loose eventual duplicates during conversion) but I cannot figure out how to get a Set[String] from this method:

import scala.collection.JavaConverters._
import org.openqa.selenium.htmlunit.HtmlUnitDriver

class Abc {

    val driver: HtmlUnitDriver 

    def collect(patterns: Set[String]): Set[String] = {
      patterns.map{ pattern => 
        driver.findElementsByXPath(pattern).asScala.map{ link =>    
           link.getAttribute("href") 
        } 
      }
    }

}

Could you please help me?

War es hilfreich?

Lösung

You can use flatten to get a List[WebElement] and then convert it to Set

def collect(patterns: Set[String]): Set[String] = {
  patterns.map{ pattern => 
    driver.findElementsByXPath(pattern).asScala.map{ link =>    
       link.getAttribute("href") 
    } 
  }.flatten.toSet
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top