Scala中的聚合列表值 [英] Aggregate list values in Scala
问题描述
从包含名义和货币两个参数的对象列表开始,我该如何汇总每个货币的名义总数?
//样本数据
val t1 = new Trade(T150310,10000000, 英镑);
val t2 =新交易(T150311,10000000,JPY);
val t3 =新交易(T150312,10000000,USD);
val t4 =新交易(T150313,100,JPY);
val t5 =新交易(T150314,1000,GBP);
val t6 =新交易(T150315,10000,USD);
val trades = List(t1,t2,t3,t4,t5,t6);
我写了一个简单的group-by操作 Groupable
trait
带有从 Iterable
的隐式转换)将允许您按照货币
将交易分组:
trait Groupable [V]扩展Iterable [V] {
def groupBy(f:V => K):MultiMap [K,V] = {
val m = new mutable.HashMap [K,Set [V ]]与mutable.MultiMap [K,V]
foreach {v => m add(f(v),v)} // add在MultiMap中定义
m
$ b隐含def it2groupable(it:Iterable [V]):Groupable [ V] = new Groupable [V] {
def elements = it.elements
}
Groupable
只是简单地提供一种从 Iterable $ c中的每个项目提取键的方法$ c>然后将所有这些具有相同键的项目分组。所以,在你的情况下:
// mm是一个MultiMap [Currency,Trade]
val mm = trades groupBy {_.currency}
您现在可以做一个非常简单的 mapElements
( mm
是一个 Map
)和一个 foldLeft
(或 /:
- 非常值得理解 foldLeft
操作符,因为它可以对集合进行非常简洁的聚合)获得总和:
$ $ $ $ $ $ $ $ $ $> $总和:Map [Currency,Int] = mm mapElements {ts =>
(0 /:ts){(sum,t)=> sum + t.notional}
}
如果我犯了一些错误,最后一行。 ts
是 mm
的值,当然是 Iterable [Trade]
。
I am learning Scala and exploring some of the functional aspects of the language.
Starting with a list of objects containing two parameters notional and currency, how can I aggregate the total notional per currency?
//sample data
val t1 = new Trade("T150310", 10000000, "GBP");
val t2 = new Trade("T150311", 10000000, "JPY");
val t3 = new Trade("T150312", 10000000, "USD");
val t4 = new Trade("T150313", 100, "JPY");
val t5 = new Trade("T150314", 1000, "GBP");
val t6 = new Trade("T150315", 10000, "USD");
val trades = List(t1, t2, t3, t4, t5, t6);
I wrote a simple group-by operation (actually a Groupable
trait
with an implicit conversion from an Iterable
) which would allow you to group your trades by their currency
:
trait Groupable[V] extends Iterable[V] {
def groupBy(f: V => K): MultiMap[K, V] = {
val m = new mutable.HashMap[K, Set[V]] with mutable.MultiMap[K, V]
foreach { v => m add (f(v), v) } //add is defined in MultiMap
m
}
}
implicit def it2groupable(it: Iterable[V]): Groupable[V] = new Groupable[V] {
def elements = it.elements
}
So Groupable
is simply providing a way to extract a key from each item in an Iterable
and then grouping all such items which have the same key. So, in your case:
//mm is a MultiMap[Currency, Trade]
val mm = trades groupBy { _.currency }
You can now do a quite simple mapElements
(mm
is a Map
) and a foldLeft
(or /:
- well worth understanding the foldLeft
operator as it enables extremely concise aggregations over collections) to get the sum:
val sums: Map[Currency, Int] = mm mapElements { ts =>
(0 /: ts) { (sum,t) => sum + t.notional }
}
Apologies if I've made some mistakes in that last line. ts
are the values of mm
, which are (of course) Iterable[Trade]
.
这篇关于Scala中的聚合列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!