Skip to content
Advertisement

Creating a Map from an Array of int – Operator ‘%’ cannot be applied to ‘java.lang.Object’

I have code like this, which is supposed to create a Map from an array of integers. The key represents the number of digits.

JavaScript

The problem is in the line with mapping(). I’m getting an error:

JavaScript

Does someone know how to solve this?

Advertisement

Answer

The flavor of collect() that expects a Collector as an argument isn’t available with primitive streams. Even without a modulus operator %, your code will not compile – comment out the downstream collector of groupingBy() to see what I’m talking about.

You need to apply boxed() operation in order to convert an IntStream into a stream of objects Stream<Integer>.

Your method might look like this:

JavaScript

I’ve changed the classifier function of groupingBy() to be more readable.

Advertisement