0

I am following some tutorials on Java Streams and it looks like all these Tutorials are already outdated (or obviously I don't get it)

 var list = Arrays.stream(new int[] {1,2,3,4,5,6})
            .filter(x -> x > 3)
            .collect(toList());

It tells me this error:

Expected 3 arguments but found 1

But every tutorial is using exactly a collect code like this.

What is going wrong?

leopal
  • 4,711
  • 1
  • 25
  • 35
Loading
  • 1,098
  • 1
  • 12
  • 25

3 Answers3

7

Arrays.stream(new int[] {1,2,3,4,5,6}) creates an IntStream, which doesn't have a collect method taking a single parameter (collect method of IntStream has the signature - <R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner)). Even if it did, toList() wouldn't be applicable, since Java doesn't allow List<int> (i.e. Lists with primitive elements). The elements of a List must be of reference type.

You can work with the wrapper Integer type instead:

var list = Arrays.stream(new Integer[] {1,2,3,4,5,6})
        .filter(x -> x > 3)
        .collect(toList());

Or keep working with an IntStream, and box it to a Stream<Integer> later in order to collect the elements to a List<Integer>:

var list = Arrays.stream(new int[] {1,2,3,4,5,6})
                 .filter(x -> x > 3)
                 .boxed()
                 .collect(toList());

If you wish to to keep working with ints, you can produce an int array from the elements of the filtered IntStream:

var array = Arrays.stream(new int[] {1,2,3,4,5,6})
                  .filter(x -> x > 3)
                  .toArray();
Eran
  • 387,369
  • 54
  • 702
  • 768
3

Arrays.stream(new int[] {1,2,3,4,5,6}) will return an IntStream, not a normal Stream<Integer>.

You could convert it to a Stream<Integer> with .boxed():

 var list = Arrays.stream(new int[] {1,2,3,4,5,6})
            .filter(x -> x > 3)
            .boxed()
            .collect(toList());
Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
-1

Have a look at this: About collect (supplier, accumulator, combiner)

and this will solve your problem:

ArrayList<Object> collect = Arrays.stream(new int[] { 1, 2, 3, 4, 5, 6 }).filter(x -> x > 3)
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

collect here takes three params Supplier,BiConsumer,BiConsumer You were giving only one that's why the exception. Hope it helps:)

DevApp
  • 55
  • 1
  • 7