有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Guava:是否可能不使用多重映射映射所有条目。索引()?

我收集了一些文件,其中一些不符合某些要求,而另一些则可以。我想在一次迭代中对这些文件进行索引化,并丢弃无用的文件。 我想在一次迭代中完成,因为这个数字相当大

所以,我在考虑使用多重贴图。索引():

// This is the file list to work on
Collection<File> fileList = FileUtils.listFiles(pathToCtrFiles,
                                                new String[]{"gz"},false);

// Now I want to index the files according to some condition in the file name (a pattern)
ImmutableListMultimap<ENBEquipment, File> mappedFiles = Multimaps.index(fileList, 
new Function<File,ENBEquipment>()
{
    @Override
    public ENBEquipment apply(File input)
    {
        Matcher m = p.matcher(input.getName());
        if (m.matches()){
            return enodebByMacroEnbIdMap.get(m.group(2));
        }

        // I am not interesting in these files. What can I do?
        return null;
    }
});

但是,不可能按照API中的规定执行:

Throws: NullPointerException - if any of the following cases is true: values is null keyFunction is null An element in values is null keyFunction returns null for any element of values

所以我的问题是,你有没有一个优雅的方法来做到这一点,而不必重复文件列表两次

注意:我想返回一个伪元素,但是返回的列表是不可变的(不可能删除它)


共 (2) 个答案

  1. # 1 楼答案

    创建新列表时,可以删除虚拟元素。但使用假人并不是很干净

    我想,在将fileList传递到Multimaps.index之前,您可以简单地过滤它。过滤谓词应该只测试匿名函数是否返回non null

  2. # 2 楼答案

    在这种情况下,只需手动进行索引(如果您遗漏了一些值,那么您甚至都不是真正的索引)

    ImmutableListMultimap.Builder<ENBEquipment, File> builder =
        ImmutableListMultimap.builder();
    for (File file : fileList) {
      Matcher m = p.matcher(file.getName());
      if (m.matches()) {
        builder.put(enodebByMacroEnbIdMap.get(m.group(2)), file);
      }
    }
    ImmutableListMultimap<ENBEquipment, File> mappedFiles = builder.build();
    

    它的行数更少,可读性也更高