有 Java 编程相关的问题?

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

如何在Java中复制除1个键以外的键值列表?

在Java中,我有一个key:value对primaryList的列表,现在我想复制除了primaryListExceptDate中的一个键日期之外的完整列表。有人能帮我吗?我知道我们可以用for循环来完成,但我想知道还有其他有效的方法吗


共 (3) 个答案

  1. # 1 楼答案

    我不知道它是否更有效,但您可以先复制列表,然后使用迭代器对其进行迭代,并删除键为“date”的条目

    编辑:类似这样的内容:

    List<Record> primaryList = ...;
    List<Record> primaryListExceptDate = new ArrayList<>(primaryList );
    Iterator<Record> it = primaryListExceptDate.iterator();
    while(it.hasNext()) {
        Record record = it.next();
        if (record.getKey().equals("date")) {
            it.remove();
        }
    }
    
  2. # 2 楼答案

    尝试使用foreach构造将数据复制到另一个列表中,并使用if来排除您不感兴趣的对象。您可能认为这不是一种有效的方法,但API提供的大多数方法都具有O(n)复杂性。 我认为这是最简单的方法。您还可以使用List-property方法来复制列表,然后删除对象,但如果您考虑性能,这可能会有点麻烦

    无论如何,我建议您使用Map Collection:当使用键:值对时,它会帮助您,而且非常有效!在这种情况下,列表是无用的

  3. # 3 楼答案

    据我所知,您有一个Record对象的列表,这些对象将值对保留为key,value

    然后您可以使用Streamapi来做您想要做的事情。比如:

    List<Record> primaryListExceptDate = primaryList.stream()
       .filter(record -> !record.getKey().equals(unwantedDateInstance))
       .collect(Collectors.toList());
    

    这将为您提供一个新列表,其中没有带有该不需要的日期的Record

    更新:您要求提供一个Vector示例

    我做了这个测试,效果很好,d2被移除了Vector实现了List,因此可以强制转换它Collectors没有toVector方法,因为Vector已过时:

    public class Testa {
    
    public static void main(String[] args) {
        Date d1 = new Date(100,1,2);
        Date d2 = new Date(101,2,3);
        Date d3 = new Date(102,3,4);
        Date test = new Date(101,2,3);
    
        Vector<Record> primaryList = new Vector<>();
        primaryList.add(new Record(d1, new Object()));
        primaryList.add(new Record(d2, new Object()));
        primaryList.add(new Record(d3, new Object()));
    
        List<Record> primaryListExceptDate = primaryList.stream()
                   .filter(record -> !record.getKey().equals(test))
                   .collect(Collectors.toList());
    
        primaryListExceptDate.forEach(r -> System.out.println(r.getKey().toString()));
    }
    
    static class Record {
        Date key;
        Object value;
    
        public Record(Date k, Object v) {
            this.key = k;
            this.value = v;
        }
    
        public Date getKey() {
            return key;
        }
    }
    }