Arrays 消除与映射/集合(Groovy)的混淆

Arrays 消除与映射/集合(Groovy)的混淆,arrays,list,collections,groovy,maps,Arrays,List,Collections,Groovy,Maps,我定义了一个集合,该集合应该在一个选项卡分隔的文本文件中映射一行的两部分: def fileMatches = [:].withDefault{[]} new File('C:\\BRUCE\\ForensicAll.txt').eachLine { line -> def (source, matches) = line.split (/\t/)[0, 2] fileMatches[source] << (matches as int)} def fileMatches=

我定义了一个集合,该集合应该在一个选项卡分隔的文本文件中映射一行的两部分:

def fileMatches = [:].withDefault{[]}

new File('C:\\BRUCE\\ForensicAll.txt').eachLine { line ->
def (source, matches) = line.split (/\t/)[0, 2]
fileMatches[source] << (matches as int)}
def fileMatches=[:].withDefault{[]}
新文件('C:\\BRUCE\\ForensicCall.txt')。eachLine{line->
def(源,匹配)=line.split(/\t/)[0,2]

fileMatches[source]我不太清楚您想做什么。例如,您如何处理两个值不同而不是相同的行(这似乎是您的代码所暗示的)?映射需要唯一的键,因此如果它有多个值,您不能将
filename
用作键

也就是说,您可以使用结果所隐含的数据获得您想要的结果,方法是:

def fileMatches = [:]
new File('C:\\BRUCE\ForensicAll.txt').eachLine { line ->
    def (source, matches) = line.split(/\t/)[0,2]
    fileMatches[source] = (matches as int)
}
但这会破坏数据(即,您总是以文件最后一行的第二个值结束。如果这不是您想要的,您可能需要在此处重新考虑您的数据结构

或者,假设您需要唯一的值,可以执行以下操作:

def fileMatches = [:].withDefault([] as Set)
new File('C:\\BRUCE\ForensicAll.txt').eachLine { line ->
    def (source, matches) = line.split(/\t/)[0,2]
    fileMatches[source] << (matches[1] as int)
}
def fileMatches=[:].withDefault([]作为设置)
新文件('C:\\BRUCE\ForensicAll.txt')。eachLine{line->
def(源,匹配)=行分割(/\t/)[0,2]

fileMatches[source]谢谢。我有很多行文本是这样的:
C:\cygwin\home\pro services\git\projectdb\project\counter.cpp 15 421
(注意:这些是用制表符分隔的)。文件中的每一行都有一个唯一的路径,如
C:\cygwin\…
(在我的问题中,我可能会混淆地将其符号化为
filename
)和唯一的数字,我想使用
line.split(/\t/)[0,2]
将每个唯一路径映射到它所在行的第二个数字,以获取(集合?)中的条目看起来是这样的:
C:\cygwin\etc:421
。我们的主要目标是稍后用映射到它们的10个最大值来隔离路径。@blaughli:那么,我认为我刚刚更新的第一个示例应该符合您的情况……尝试附加
(将[1]匹配为int)
to
fileMatches
如果不给它一个默认设置,就会抛出一个NullPointerException