Skip to content

Instantly share code, notes, and snippets.

@vidhill
Last active November 9, 2018 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vidhill/ef9ef624cbb3a4f4dea65379a611493d to your computer and use it in GitHub Desktop.
Save vidhill/ef9ef624cbb3a4f4dea65379a611493d to your computer and use it in GitHub Desktop.
Java reduce/collection, the many ways to skin a cat
// Option A
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.reduce(0, (aggValue, current) -> {
Integer value = (Integer) current.getValue();
return aggValue + value;
}, (aLong1, aLong2) -> aLong1);
// Option B
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.reduce(0, (aggValue, current) -> {
Integer value = (Integer) current.getValue();
return aggValue + value;
}, Integer::compareTo);
// Option C
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.map(entry -> (Integer) entry.getValue())
.reduce(0, (aggValue, current) -> {
return aggValue + current;
}, Integer::compareTo);
// Option D
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.map(entry -> (Integer) entry.getValue())
.mapToInt(Integer::intValue) // converts it to IntStream
.sum();
// Option E
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.map(SimpleEntry::getValue)
.map(Integer.class::cast)
.mapToInt(Integer::intValue)
.sum();
// Option F
Integer totalFixedRateResultCount = fixedRateCounts
.stream()
.map(SimpleEntry::getValue)
.map(Integer.class::cast)
.collect(Collectors.summingInt(Integer::intValue));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment