I wrote this function that roughly just combines force vectors applied to different boxes. What it does isn't so important, it's the fact I wrote it in a streams-style and then looked at it and thought - I can barely understand this and I wrote it... So I wrote it in the plain-java way and it looks to me a million times simpler.
I don't want to get into a "use what you think's best" type of debate, but I do want to think about is there ways to represent this problem using streams and lamdas that doesn't look obtuse
Map<Box, Force> results =
delegates.stream()
.map( pressure -> pressure.calculate( c ) )
.reduce(
new HashMap<Box,Force>(),
(acc, next)-> {
next.entrySet().forEach(entry -> {
ForceaccVector = acc.get(entry.getKey());
if (accVector == null) {
accVector = new Force();
acc.put(entry.getKey(), accVector);
}
accVector.x += entry.getValue().x;
accVector.y += entry.getValue().y;
});
return acc;
}
);
return results;
Traditional version (seems simpler)
Map<Box,Force> acc = new HashMap<Box,Force>();
for( Pressure pressure : delegates ) {
Map<Box,Vector> next = pressure.calculate( c );
for( Map.Entry<Box,Force> entry : next.entrySet() ) {
Force accVector = acc.get( entry.getKey() );
if (accVector == null) {
accVector = new Force();
acc.put(entry.getKey(), accVector);
}
accVector.x += entry.getValue().x;
accVector.y += entry.getValue().y;
}
}
I am totally aware that there are specific situations where lamdas are amazing and streams too, but I was kind of sad that it didn't give my code here such an advantage. Is there a better way to arrange this or is there some advantages I'm missing here ?
Edit: One big advantage is that you can fairly easily add in a "ParallelStream" into streams and it will use multiple cores to handle different sections. That is a big benefit over old-school foreach
Edit2: /u/rmslashusr has posted this very elegant solution, which is everything I hoped it would look like. https://www.reddit.com/r/javahelp/comments/67nsav/opinion_i_want_to_like_streams_and_lamdas_but/dgrx1ot/
return delegates.stream()
.flatMap( pressure -> pressure.calc(c).entrySet().stream() )
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
Force::add
)
);