1
기능/스칼라 방식에서 각 요소의 발생 횟수를 찾는 가장 좋은 방법은 무엇입니까?기능적 방식으로 내부 컬렉션에서 발생 수 찾기
결과Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
, 나는
Set(("a", 1), ("b", 3), ("c", 2))
감사합니다 같은 것을 필요로한다!
기능/스칼라 방식에서 각 요소의 발생 횟수를 찾는 가장 좋은 방법은 무엇입니까?기능적 방식으로 내부 컬렉션에서 발생 수 찾기
결과Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
, 나는
Set(("a", 1), ("b", 3), ("c", 2))
감사합니다 같은 것을 필요로한다!
scala> val s = Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
s: Seq[scala.collection.immutable.Set[String]] =
List(Set(a, b, c), Set(b), Set(b, c))
scala> s.flatten
res0: Seq[String] =
List(a, b, c, b, b, c)
scala> s.flatten.groupBy(identity)
res3: scala.collection.immutable.Map[String,Seq[String]] =
Map(b -> List(b, b, b), a -> List(a), c -> List(c, c))
scala> s.flatten.groupBy(identity).map { case (k, v) => (k, v.size) }.toSet
res7: scala.collection.immutable.Set[(String, Int)] =
Set((b,3), (a,1), (c,2))
scala> val x = Seq(Set("a", "b", "c"), Set("b"), Set("b", "c"))
x: Seq[scala.collection.immutable.Set[String]] = List(Set(a, b, c), Set(b), Set(b, c))
scala> (x.flatten groupBy identity mapValues (_.size)).toSet
res3: scala.collection.immutable.Set[(String, Int)] = Set((b,3), (a,1), (c,2))