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

时间:2017-08-31 08:33:31

标签: java list arraylist

我在Java中有1个key:value pair primaryList列表,现在我想复制除primaryListExceptDate中的一个关键日期之外的完整列表。谁可以帮我这个事?我知道我们可以使用for循环但我想知道有没有其他有效的方法呢?

3 个答案:

答案 0 :(得分:2)

据我所知,你有一个Record对象列表,它们将值对保存为键值!?

然后你可以用Stream api做你想做的事。类似的东西:

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

答案 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 :(得分:0)

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

无论如何,我建议你使用Map Collection:当你使用一个键:值对时它来拯救你,它非常有效!在这种情况下,列表没用。