Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removeIf() of List not working throwing - UnsupportedOperationException [duplicate]

When I try to remove the element from the list using removeIf(), It is throwing UnsupportedOperationException

public class T {
        public static void main(String[] args) {
        String[] arr = new String[] { "1", "2", "3" };
        List<String> stringList = Arrays.asList(arr);
        stringList.removeIf((String string) -> string.equals("2"));
    }
}

Can some one help me understand why this is happening and how can I rectify this ?

like image 641
Sachin Sachdeva Avatar asked Sep 04 '25 03:09

Sachin Sachdeva


2 Answers

Arrays.asList(arr) returns a fixed sized List, so you can't add or remove elements from it (only replace existing elements).

Create an ArrayList instead:

List<String> stringList = new ArrayList<>(Arrays.asList(arr));
like image 74
Eran Avatar answered Sep 07 '25 15:09

Eran


Since you are explicitly calling Arrays.asList, consider the alternative of not doing that, and create the filtered list directly:

Stream.of(arr)
    .filter(string -> !string.equals("2"))
    .collect(Collectors.toList())
like image 36
Andy Turner Avatar answered Sep 07 '25 16:09

Andy Turner