3

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 ?

T-Bag
  • 10,916
  • 3
  • 54
  • 118

2 Answers2

10

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));
Eran
  • 387,369
  • 54
  • 702
  • 768
1

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())
Andy Turner
  • 137,514
  • 11
  • 162
  • 243