1

This is the first time I am trying to use the new Stream API in Java 1.8 and I have to admit that I have some problem understanding it...

Basically, let's say I have an int array containing same values. For example:

int[] intArray = new int[]{1,2,3,4,5};

Now, I'd like to use the Stream API and store in a List the indexes of this intArray where the value is higher than 3.

This is what my code looks like:

int[] intArray = new int[]{1,2,3,4,5};
List<Integer> indexes = IntStream.range(0, intArray.length)
                                 .filter(i -> intArray[i] > 3)
                                 .sorted()
                                 .collect(Collectors.toList());

But I get a compilation failure saying "The method collect(Supplier, ObjIntConsumer, BiConsumer) in the type IntStream is not applicable for the arguments (Collector >)".

I'd like indexes to contain 3 and 4.

1
  • 1
    An IntStream is a Stream of primitive int values, not of Integer objects. So when you create a List, those primitives values must be boxed to their corresponding Integer (because there is no IntList, i.e. a List which would hold primitive values). So you need to call boxed(). Commented Nov 22, 2015 at 15:10

2 Answers 2

2

You should box your IntStream into a Stream<Integer> :

List<Integer> indexes = IntStream.range(0, intArray.length)
                             .filter(i -> intArray[i] > 3)
                             .sorted()
                             .boxed()
                             .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

Note that there's no point in .sorted() call
0

You could use different logic:

int[] c = {-1}; // array is effectively final
Arrays.stream(intArray)
  .map(n -> ++c[0] >= 0 && n > 3 ? c[0] : -1)
  .filter(n -> n > -1)
  .boxed()
  .collect(Collectors.toList());

This turns every n > 3 into its index then filters out the rest, which avoids a sort.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.