val list = List(1,2,4,2,4,7,3,2,4)
次のように実装したいと思います: list.count(2)
(3 を返します)。
他の回答の1つのややクリーンなバージョンは次のとおりです。
val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(identity).mapValues(_.size)
Map
元のシーケンスの各アイテムのカウントを与える:
Map(banana -> 1, oranges -> 3, apple -> 3)
質問は、特定のアイテムの数を見つける方法を尋ねます。このアプローチでは、次のように、目的の要素をそのカウント値にマッピングする必要があります。
s.groupBy(identity).mapValues(_.size)("apple")
scala コレクションには次のものがありますcount
。list.count(_ == 2)
私は Sharath Prabhal と同じ問題を抱えていましたが、別の (より明確な) 解決策を得ました。
val s = Seq("apple", "oranges", "apple", "banana", "apple", "oranges", "oranges")
s.groupBy(l => l).map(t => (t._1, t._2.length))
結果として:
Map(banana -> 1, oranges -> 3, apple -> 3)
list.groupBy(i=>i).mapValues(_.size)
与える
Map[Int, Int] = Map(1 -> 1, 2 -> 3, 7 -> 1, 3 -> 1, 4 -> 3)
(i=>i)
組み込みidentity
関数に置き換えることができることに注意してください。
list.groupBy(identity).mapValues(_.size)
val list = List(1, 2, 4, 2, 4, 7, 3, 2, 4)
// Using the provided count method this would yield the occurrences of each value in the list:
l map(x => l.count(_ == x))
List[Int] = List(1, 3, 3, 3, 3, 1, 1, 3, 3)
// This will yield a list of pairs where the first number is the number from the original list and the second number represents how often the first number occurs in the list:
l map(x => (x, l.count(_ == x)))
// outputs => List[(Int, Int)] = List((1,1), (2,3), (4,3), (2,3), (4,3), (7,1), (3,1), (2,3), (4,3))
のように使用したい場合は、 Implicit Classlist.count(2)
を使用して実装する必要があります。
implicit class Count[T](list: List[T]) {
def count(n: T): Int = list.count(_ == n)
}
List(1,2,4,2,4,7,3,2,4).count(2) // returns 3
List(1,2,4,2,4,7,3,2,4).count(5) // returns 0
簡潔な答え:
import scalaz._, Scalaz._
xs.foldMap(x => Map(x -> 1))
長い答え:
与えられたScalazの使用。
import scalaz._, Scalaz._
val xs = List('a, 'b, 'c, 'c, 'a, 'a, 'b, 'd)
次に、これらすべて(単純化されていないものから単純化されたものへの順序で)
xs.map(x => Map(x -> 1)).foldMap(identity)
xs.map(x => Map(x -> 1)).foldMap()
xs.map(x => Map(x -> 1)).suml
xs.map(_ -> 1).foldMap(Map(_))
xs.foldMap(x => Map(x -> 1))
収率
Map('b -> 2, 'a -> 3, 'c -> 2, 'd -> 1)
猫を使う
import cats.implicits._
"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.combineAll
"Alphabet".toLowerCase().map(c => Map(c -> 1)).toList.foldMap(identity)