0

My question is short, why does it not compile?

final ArrayList <Integer> list = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());

The problem occurs in Collectors.toList() part.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
azalut
  • 4,094
  • 7
  • 33
  • 46

1 Answers1

3

Collectors.toList() returns some List implementation that doesn't have to be ArrayList, and probably isn't.

Try

final List <Integer> list = IntStream.rangeClosed(1, 20)
                                     .boxed()
                                     .collect(Collectors.toList());

You can use collect(Collectors.toCollection(ArrayList::new)) if you specifically need an ArrayList.

final ArrayList <Integer> list = IntStream.rangeClosed(1, 20)
                                          .boxed()
                                          .collect(Collectors.toCollection(ArrayList::new));
Eran
  • 387,369
  • 54
  • 702
  • 768