blue-sky blue-sky - 11 months ago 65
Scala Question

Remove some data as part of groupBy

This code :

import scala.collection.immutable.Set;

object Update extends App {

val ss: List[Set[(String, String)]] = List(Set(
("sentance1", "url1"),
("sentance2", "url1"),
("sentance3", "url2")

val linesWithUrl: List[Map[String, Set[(String, String)]]] = => m.groupBy(_._2))


returns :

Map(url1 -> Set((sentance1,url1), (sentance2,url1)), url2 -> Set((sentance3,url2)))

I want to return just the sentences as values within the map :

Map(url1 -> Set((sentance1), (sentance2)), url2 -> Set((sentance3)))

Method I'm considering is to iterate over linesWithUrl and create a map with just the required values, but can the expected data structure be created in an alternative way ?


Can't think of anything alternative. I believe what you proposed - mapping over it afterwards - is the correct way to do it: => m.groupBy(_._2).mapValues(

I'm not saying this as some kind of rule, but personally I usually strive for solutions that are simplest and most obvious unless there is a performance issue. Doing it any other way would probably make it more difficult for anyone who's trying to understand your code afterwards.

EDIT: As a style-related side note, I noticed now that you used m => m.groupBy. If that's how you prefer, also change my to something like s => (consistency is a great thing :)). It's probably unnecessary for tuples though.