英文:
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 异常。
那么我是不是做错了什么,还是有没有其他方法可以在这种情况下使用。
英文:
For example,
List<String> list1 = Arrays.asList("a", "b", "c","d");
List<String> list2 = Arrays.asList("a", "b", "e");
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.
So is there something that I making mistake or is there any method to use for such scenarios.
答案1
得分: 1
你需要一个ArrayList来执行removeAll
操作。Arrays.asList
和new ArrayList
之间存在区别。
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
.
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);
}
Output:
[c, d]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论