Last active
November 9, 2018 13:46
-
-
Save vidhill/ef9ef624cbb3a4f4dea65379a611493d to your computer and use it in GitHub Desktop.
Java reduce/collection, the many ways to skin a cat
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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