如何使用Scala删除重复的键并合并列表的其他键值? [英] How to remove duplicate keys and merge other key-values of list using scala?
问题描述
我正在遵循List [JSONObject]结构作为某些代码片段的输出-
I am getting following List[JSONObject] structure as a output of some snippet-
List(List({
"groupName": "group1",
"maxSeverity": -1,
"hostCount": 3,
"members": [
"192.168.20.11",
"192.168.20.52",
"192.168.20.53"
]
}),
List(),
List({
"groupName": "group1",
"maxSeverity": -1,
"hostCount": 2,
"members": [
"192.168.20.20",
"192.168.20.52"
]
}))
我想合并整个输出以形成一个包含以下内容的列表: 1)组名
I want to merge whole output to form a list which contains - 1) group name
2)严重性-所有列表元素中的严重性最低
2) severity - which will be minimum from all list elements
3)hostcout-从所有列表元素中添加主机计数
3) hostcout - addition of hostcount from all list elements
4)成员-相似的数组,所有列表元素中没有重复值.
4) members - similar array without duplicate values from all list elements.
所以输出将有点像这样-
So output will be somewhat like this-
List({
"groupName": "group1",
"maxSeverity": -1,
"hostCount": 5,
"members": [
"192.168.20.11",
"192.168.20.52",
"192.168.20.53",
"192.168.20.20",
"192.168.20.52"
]
})
如何将整个列表合并为一个列表以获得上述输出?
How do I merge whole list to a single list to get above mentioned output???
推荐答案
请考虑使用Jackson将其解析为case类,然后以这种方式使用数据.
Consider using Jackson to parse these into a case class, and then work with the data that way.
object JsonMerge {
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
case class ServerGroup(groupName: String, hostCount: Int, maxSeverity: Int, members: Iterable[String])
def collapseGroup(groups: List[ServerGroup]): ServerGroup = {
val members = groups.flatMap(_.members).toSet
ServerGroup(groups.head.groupName, members.size, groups.map(_.maxSeverity).min, members)
}
def main(args: Array[String]) {
val objectMapper = new ObjectMapper with ScalaObjectMapper
objectMapper.registerModule(DefaultScalaModule)
val allGroups = objectMapper.readValue[List[ServerGroup]](rawData)
val output = allGroups.groupBy(_.groupName).values.map(collapseGroup)
objectMapper.writerWithDefaultPrettyPrinter().writeValue(System.out, output)
}
val rawData = """
[{
"groupName": "group1",
"hostCount": 3,
"maxSeverity": -1,
"members": [
"192.168.20.11",
"192.168.20.52",
"192.168.20.53"
]
},{
"groupName": "group1",
"hostCount": 2,
"maxSeverity": -1,
"members": [
"192.168.20.20",
"192.168.20.52"
]
},{
"groupName": "group2",
"hostCount": 1,
"maxSeverity": 2,
"members": [
"192.168.20.52"
]
}]"""
}
具有以下输出:
[ {
"groupName" : "group2",
"hostCount" : 1,
"maxSeverity" : 2,
"members" : [ "192.168.20.52" ]
}, {
"groupName" : "group1",
"hostCount" : 4,
"maxSeverity" : -1,
"members" : [ "192.168.20.11", "192.168.20.52", "192.168.20.53", "192.168.20.20" ]
} ]
这篇关于如何使用Scala删除重复的键并合并列表的其他键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!