Collections removeAll method

前端 未结 5 595

I would like to know if something like below is possible,

list.removeAll(namesToRemove)

I hope the context is understandable.

The

5条回答
  •  悲哀的现实
    2021-01-07 09:47

    Java 8:

    list.removeIf(obj -> namesToRemove.contains(obj.getName()));
    

    Java 7 and older:

    Iterator iter = list.iterator();
    while (iter.hasNext())
        if (namesToRemove.contains(iter.next().getName()))
            iter.remove();
    

    Note that both alternatives have quadratic complexity. You can make it linear by doing

    Set namesToRemoveSet = new HashSet<>(namesToRemove);
    

    before the snippets, and use namesToRemoveSet instead of namesToRemove.

提交回复
热议问题