How to remove all elements from List1 which are contained in List2 if List2 contains some of element which are not present in List1?

huangapple go评论88阅读模式
英文:

How to remove all elements from List1 which are contained in List2 if List2 contains some of element which are not present in List1?

问题

例如,

List<String> list1 = Arrays.asList("a", "b", "c", "d");
List<String> list2 = Arrays.asList("a", "b", "e");

我想从list1中删除所有在list2中的元素,所以我做了以下操作:

list1.removeAll(list2);
return list1;

但是我得到了 UnsupportedOperationException 异常。How to remove all elements from List1 which are contained in List2 if List2 contains some of element which are not present in List1?
那么我是不是做错了什么,还是有没有其他方法可以在这种情况下使用。

英文:

For example,

List&lt;String&gt; list1 = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;,&quot;d&quot;);
List&lt;String&gt; list2 = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;e&quot;);

I want to remove all elements from list1 which are in list2, So what I did

list1.removeAll(List2);
return list1;

But I got UnsupportedOperationException.How to remove all elements from List1 which are contained in List2 if List2 contains some of element which are not present in List1?
So is there something that I making mistake or is there any method to use for such scenarios.

答案1

得分: 1

你需要一个ArrayList来执行removeAll操作。Arrays.asListnew ArrayList之间存在区别。

参考 - https://stackoverflow.com/questions/16748030/difference-between-arrays-aslistarray-and-new-arraylistintegerarrays-aslist

public static void main(String[] args){
        List<String> list1 = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
        List<String> list2 = Arrays.asList("a", "b", "e");
        list1.removeAll(list2);
        System.out.println(list1);
}

输出:

[c, d]
英文:

You need an arraylist to perform removeAll. There's a difference between Arrays.asList and new ArrayList.

Refer - https://stackoverflow.com/questions/16748030/difference-between-arrays-aslistarray-and-new-arraylistintegerarrays-aslist

public static void main(String[] args){
        List&lt;String&gt; list1 = new ArrayList&lt;&gt;(Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;,&quot;d&quot;));
        List&lt;String&gt; list2 = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;e&quot;);
        list1.removeAll(list2);
        System.out.println(list1);
}

Output:

[c, d]

huangapple
  • 本文由 发表于 2020年7月23日 15:54:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63049463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定