我是scala的新手。我想为所有波纹管数据创建地图,包含PINCODE作为键,所有其他字段作为值。
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr>
<th>PINCODE</th>
<th>Locality</th>
<th>PO_TYPE</th>
<th>TALUK</th>
<th>DISTRICT</th>
</tr>
<tr>
<td>500001</td>
<td>Hyderabad G.P.O.</td>
<td>Branch Post Office</td>
<td>Hyderabad</td>
<td>HYDERABAD</td>
</tr>
<tr>
<td>500001</td>
<td>Gandhi Bhawan</td>
<td>Branch Post Office</td>
<td>Nampally</td>
<td>HYDERABAD</td>
</tr>
<tr>
<td>500001</td>
<td>Hindi Bhawan</td>
<td>Branch Post Office</td>
<td>Nampally</td>
<td>HYDERABAD</td>
</tr>
<tr>
<td>500002</td>
<td>Hyderabad Jubilee</td>
<td>Branch Post Office</td>
<td>HYDERABAD</td>
<td>HYDERABAD</td>
</tr>
<tr>
<td>500002</td>
<td>Moghalpura Branch</td>
<td>Post Office</td>
<td>HYDERABAD</td>
<td>HYDERABAD</td>
</tr>
</table>
</body>
</html>
例如:(输出类似于bellow)
(500001,(Hyderabad G.P.O.,Branch Post Office,Hyderabad,HYDERABAD), (甘地巴哈,分支邮局,海南省,海得拉巴), (Hindi Bhawan,分支邮局,Nampally,海得拉巴))
(500002,(Hyderabad Jubilee,Branch Post Office,HYDERABAD,HYDERABAD), (海德拉巴,海得拉巴邮局Moghalpura分店))
提前致谢
答案 0 :(得分:2)
实际上,Map
应该uniquely map
key
到value
。
因此,如果您想在同一个密钥上存储多个值(假设为String
s),则可以将其设为Map[String, List[String]]
。
val map: Map[String, List[String]] = Map(
"1" -> List("val_1_1", "val_1_2", "val_1_3"),
"2" -> List("val_2_1", "val_2_2")
)
但是......至于你的情况,看起来你正在尝试拥有&#34;价值观&#34;它们不是String
,而是更像地址描述。
在这种情况下,为什么不为地址创建一个类?
case class Address(
locality: String,
poType: String,
taluk: String,
district: String
)
// Now you can have you map
val map: Map[String, List[Address]] = Map(
"500001" -> List(Address("Hyderabad G.P.O.", "Branch Post Office", "Hyderabad", "HYDERABAD"))
)
// define a function that we will use to add addresses without over-writing
def updateMapByAddingAddressWithPincode(
map: Map[String, List[String]],
pincode: String,
address: Address
) = {
val existingAddressListForPincode = map.getOrElse(pincode, default = List.empty[Address])
map + (pincode -> address :: existingAddressListForPincode)
}
// now lets say, you want to add another address with same pincode "500001"
val newAddress = Address("Gandhi Bhawan", "Branch Post Office", "Nampally", "HYDERABAD")
val updatedMap = updateMapByAddingAddressWithPincode(
map,
"500001",
newAddress
)
答案 1 :(得分:2)
您想要MultiMap,例如:
val mm = new mutable.HashMap[Int, mutable.Set[String]] with mutable.MultiMap[Int, String]
mm.addBinding(500001, "a")
mm.addBinding(500003, "b")
mm.addBinding(500001, "c")
val l = mm.getOrElse(500001, List())
println(l)
对于List
值类型,您可以将MultiMap
值类型设置为:List[String]
,如:
val mm = new mutable.HashMap[Int, mutable.Set[List[String]]] with mutable.MultiMap[Int, List[String]]
mm.addBinding(500001, List("a", "b"))
mm.addBinding(500003, List("b", "c"))
mm.addBinding(500001, List("c", "D"))
val l = mm.getOrElse(500001, Set())
println(l)
输出:
Set(List(e, f), List(a, b))
答案 2 :(得分:0)
基本上,您可以将+
与此处所述的特征Map[String, Set[String]]
混合使用:
http://www.scala-lang.org/api/current/scala/collection/mutable/MultiMap.html
样品:
MultiMap