Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Stream to IntStream

I have a feeling I'm missing something here. I found myself doing the following

private static int getHighestValue(Map<Character, Integer> countMap) {     return countMap.values().stream().mapToInt(Integer::intValue).max().getAsInt(); } 

My problem is with the silly conversion from Stream to IntStream via the mapToInt(Integer::intValue)

Is there a better way of doing the conversion? all this is to avoid using max() from Stream, which requires passing a Comparator but the question is specifically on the convertion of Stream to IntStream

like image 328
Hilikus Avatar asked Jan 18 '15 21:01

Hilikus


People also ask

What is the difference between Stream and IntStream?

IntStream is a stream of primitive int values. Stream<Integer> is a stream of Integer objects.

What is Java Util Stream IntStream?

Java IntStream class is a specialization of Stream interface for int primitive. It represents a stream of primitive int-valued elements supporting sequential and parallel aggregate operations. IntStream is part of the java. util. stream package and implements AutoCloseable and BaseStream interfaces.


2 Answers

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.

like image 148
Holger Avatar answered Oct 04 '22 03:10

Holger


I realize you are trying to avoid a comparator, but you could use the built-in for this by referring to Integer.compareTo:

private static int getHighestValue(Map<Character, Integer> countMap) {     return countMap.values().stream().max(Integer::compareTo).get(); } 

Or as @fge suggests, using ::compare:

private static int getHighestValue(Map<Character, Integer> countMap) {     return countMap.values().stream().max(Integer::compare).get(); } 
like image 30
Todd Avatar answered Oct 04 '22 03:10

Todd