Map one value to all values with a common relation Scala

☆樱花仙子☆ 提交于 2019-12-24 08:39:14

问题


Having a set of data:

{sentenceA1}{\t}{sentenceB1}  
{sentenceA1}{\t}{sentenceB2}  
{sentenceA2}{\t}{sentenceB1}   
{sentenceA3}{\t}{sentenceB1}   
{sentenceA4}{\t}{sentenceB2}    

I want to map a sentenceA to all the sentences that have a common sentenceB in Scala so the result will be something like this:

{sentenceA1}->{sentenceA2,sentenceA3,sentenceA4} or  

{sentenceA2}->{sentenceA1, sentenceA3}

回答1:


val lines = List(
  "sentenceA1\tsentenceB1",
  "sentenceA1\tsentenceB2",
  "sentenceA2\tsentenceB1",
  "sentenceA3\tsentenceB1",
  "sentenceA4\tsentenceB2"
)

val afterSplit = lines.map(_.split("\t"))

val ba = afterSplit
  .groupBy(_(1))
  .mapValues(_.map(_(0)))

val ab = afterSplit
  .groupBy(_(0))
  .mapValues(_.map(_(1)))

val result = ab.map { case (a, b) =>
  a -> b.foldLeft(Set[String]())(_ ++ ba(_)).diff(Set(a))
}


来源:https://stackoverflow.com/questions/26701902/map-one-value-to-all-values-with-a-common-relation-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!