The entire operation that you want to do is slightly wrong
list = list.stream()
.mapToInt(i -> 2) // every single element is transformed to "2"
.filter(i -> i == 2) // since the previous step turns everything into 2, this one will take every element
.distinct() // then you apply distinct, resulting in a single element
.boxed()
.collect(Collectors.toList());
The result is a List
with a single element with value 2
, but it's very inefficient.
If you really want to filter, then it would be easier with just:
list = list.stream()
.filter(i -> i == 2)
.collect(Collectors.toList());
Besides that your initial code :
list.clear();
list.add(2);
will fail, because Arrays.asList
will create an immutable list.
But even if you would have an ArrayList that is mutable, the difference is that with your stream approach you will not alter the source of the stream; while with you first approach you would delete everything and re-populate it with different values.