Comparing Java’s mapToInt and Reduce methods used with map

Map is a valuable tool for avoiding unwanted collisions between your keys and predefined Object’s prototype properties. It offers the ability to use objects as keys. In addition to this, Map also has useful properties, utility functions, and is Iterable. Using Map can save you some writing as compared to using Object, especially when trying to find the number of key-value pairs. Furthermore, Map can be more performant in intensive key-value operations such as addition and removal.


Question:

After researching on ‘reduce’, I recently discovered its 3 argument version which can execute a
map reduce
function in a similar manner.

String[] strarr = {"abc", "defg", "vwxyz"};
System.out.println(Arrays.stream(strarr).reduce(0, (l, s) -> l + s.length(), (s1, s2) -> s1 + s2));

I fail to perceive the superiority of this in comparison to a
maptoint
that has been reduced.

System.out.println(Arrays.stream(strarr).mapToInt(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2));

Both methods yield the accurate result of 12 and seem to function properly concurrently.

Is there a superiority between the two options, and if yes, what is the reason?


Solution 1:

Is there a superiority between the two options, and if yes, what is the reason?

The initial

reduce

strategy incurs a hidden expense related to the sport of boxing.

The utilization of

mapToInt.reduce(...)

method prevents that from happening.

The suggestion is to opt for primitive stream specializations when dealing with summation, averages, and other related calculations, as they offer better efficiency.

By the way, the code:

Arrays.stream(strarr).mapToInt(s -> s.length()).reduce(0, (s1, s2) -> s1 + s2)

can be simplified to:

Arrays.stream(strarr).mapToInt(s -> s.length()).sum();


Solution 2:


The MSDT code that takes three arguments offers greater flexibility.

 U reduce(U identity,
             BiFunction accumulator,
             BinaryOperator combiner);

When contrasted with the

IntStream.reduce

function, which only allows for

int

inputs and outputs, there are some differences.

int reduce(int identity, IntBinaryOperator op);

The three-argument version of

accumulator

can accept parameters of two distinct types.

BiFunction acc = (i, str) -> i + str.length();

Enables the exclusion of supplementary

map

tasks.

Arrays.stream(strs).reduce(0, (i, str) -> i + str.length(), Integer::sum)

Frequently Asked Questions