The IntStream class's map method maps ints to more ints, with a IntUnaryOperator (int to int), not to objects.
Generally, all streams' map method maps the type of the stream to itself, and mapToXyz maps to a different type.
Try the mapToObj method instead, which takes an IntFunction (int to object) instead.
.mapToObj(id -> new MyObject(id));
Answer from rgettman on Stack OverflowThe IntStream class's map method maps ints to more ints, with a IntUnaryOperator (int to int), not to objects.
Generally, all streams' map method maps the type of the stream to itself, and mapToXyz maps to a different type.
Try the mapToObj method instead, which takes an IntFunction (int to object) instead.
.mapToObj(id -> new MyObject(id));
Stream stream2 = intStream.mapToObj( i -> new ClassName(i));
This will convert the intstream to Stream of specified object type, mapToObj accepts a function.
There is method intStream.boxed() to convert intStream directly to Stream<Integer>
Videos
Due to type erasure, the Stream implementation has no knowledge about the type of its elements and can’t provide you with neither, a simplified max operation nor a conversion to IntStream method.
In both cases it requires a function, a Comparator or a ToIntFunction, respectively, to perform the operation using the unknown reference type of the Stream’s elements.
The simplest form for the operation you want to perform is
return countMap.values().stream().max(Comparator.naturalOrder()).get();
given the fact that the natural order comparator is implemented as a singleton. So it’s the only comparator which offers the chance of being recognized by the Stream implementation if there is any optimization regarding Comparable elements. If there’s no such optimization, it will still be the variant with the lowest memory footprint due to its singleton nature.
If you insist on doing a conversion of the Stream to an IntStream there is no way around providing a ToIntFunction and there is no predefined singleton for a Number::intValue kind of function, so using Integer::intValue is already the best choice. You could write i->i instead, which is shorter but just hiding the unboxing operation then.
Another way you could do the conversion is with a lambda: mapToInt(i -> i).
Whether you should use a lambda or a method reference is discussed in detail here, but the summary is that you should use whichever you find more readable.