清除与地图/集合(Groovy)的混淆 [英] Clearing up confusion with Maps/Collections (Groovy)

查看:142
本文介绍了清除与地图/集合(Groovy)的混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义一个集合,它应该在一个制表符分隔的文本文件中映射一行的两个部分:

I define a collection that is supposed to map two parts of a line in a tab-separated text file:

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

new File('C:\\BRUCE\\ForensicAll.txt').eachLine { line ->
def (source, matches) = line.split (/\t/)[0, 2]
fileMatches[source] << (matches as int)}

我最终输入了 [984,984] ,我想要 [filename:984] 。我不明白 fileMatches [source]<< (matches as int)工程。我如何获得我需要的集合?

I end up with entries such as filename:[984, 984] and I want [filename : 984] . I don't understand how fileMatches[source] << (matches as int) works. How might I get the kind of collection I need?

推荐答案

我不太确定我明白你在做什么。例如,如何处理一行,其中两个值是不同的,而不是相同的(这似乎是你的代码隐含的)?映射需要唯一键,因此如果具有多个值,则不能使用 filename 作为键。

I'm not quite sure I understand what you are trying to do. How, for example, would you handle a line where the two values are different instead of the same (which seems to be what is implied by your code)? A map requires unique keys, so you can't use filename as a key if it has multiple values.

也就是说,您可以使用以下结果使用结果中包含的数据获得所需的结果:

That said, you could get the result you want with the data implied by your result using:

def fileMatches = [:]
new File('C:\\BRUCE\ForensicAll.txt').eachLine { line ->
    def (source, matches) = line.split(/\t/)[0,2]
    fileMatches[source] = (matches as int)
}

但是这会破坏数据(即,你将总是最后一行文件的第二个值。

But this will clobber the data (i.e., you will always end up with the second value from the last line your file. If that's not what you want you may want to rethink your data structure here.

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

Alternatively, assuming you want unique values, you could do:

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)
}

这将导致类似 [文件名:[984,987]]

再次,它真的取决于你想要捕获的内容,如果你能提供更多的细节,你想要完成什么,你的问题可能会变得可以回答...

Again, it really depends on what you are trying to capture. If you could provide more detail on what you are trying to accomplish, your question may become answerable...

这篇关于清除与地图/集合(Groovy)的混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆