0

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.enter image description here So is there something that I making mistake or is there any method to use for such scenarios.

iamgul
  • 83
  • 9

1 Answers1

1

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

Refer - Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

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]
bigbounty
  • 16,526
  • 5
  • 37
  • 65