1

I try to remove an item from a list using lambda expression but removeIf generate an exception, why?

In this Orlacle video jdk8 8 MOOC introduce removeif with list and not arraylist. Is it right ? https://youtu.be/olKF7VpJMfg?list=PLMod1hYiIvSZL1xclvHcsV2dMiminf19x&t=137

public static void main(String[] args){
        List<String> parole = Arrays.asList("Lambda ", "expressions ", "are ", "cool ");
Predicate <String> findAre= s->"are ".equals(s);         
        parole.removeIf(findAre);
        parole.forEach( System.out::println);
            }

Here pict with code and Exception in thread "main"

fbw
  • 37
  • 5
  • Please post this as a [mcve] and include the exception as *text*. Providing a screenshot has no benefit here, and means the exception type isn't indexed... – Jon Skeet Apr 20 '17 at 08:20
  • `Arrays.asList` just wraps the array provided. You can't change the length of the array. – Peter Lawrey Apr 20 '17 at 08:21

2 Answers2

7

Arrays.asList produces a fixed sized list backed by an array, so you can't add or remove elements from it.

You can create an ArrayList in order to support removal:

List<String> parole = new ArrayList<>(Arrays.asList("Lambda ", "expressions ", "are ", "cool "));
Eran
  • 387,369
  • 54
  • 702
  • 768
0

One more suggestion, please use iterator during list iteration to remove objects from arraylist instead of for each loop, as you will get Concurrency modifying exception.

user503285
  • 125
  • 3
  • 14