3 ms·
If it were Python, I could probably write something like: sum(key.price * val for (key, val) in cart.items()) But the Java example makes me think "Wait, w
by yongjik 5y ago
If it were Python, I could probably write something like:
sum(key.price * val for (key, val) in cart.items())
But the Java example makes me think "Wait, what?"
Personally, the lesson I'm drawing is that your library shouldn't actively fight the native syntax of the language you are using - just use what your language provides, that's the cleanest and easiest way to do it.
But I guess people's tastes are different.
- forgetfulness 5y agoHalf the problem is that the BigDecimal class is kind of horrid in Java, and so is Map.Entry. The language lacks features that would make them more workable, like operator overloading, implicit constructors and destructuring/pattern matching. Now, the first two are very fair not to want in a language because they allow programmers to bring in an unlimited amount of user-defined complexity. Some destructuring however, would just make it easier to work with what's already in the language and libraries.
- stickfigure 5y agoPython's `sum()` works only on numbers and assumes an empty list sums to 0. Java's `reduce()` is quite a bit more flexible. I use Joda Money and frequently find myself doing: final Money bucks = stream.map(Thing::getPrice).reduce(Dollars.ZERO, Money::plus); If you don't pass in a baseline, you get optional: final Optional<Money> bucks = stream.map(Thing::getPrice).reduce(Money::plus); Also, StreamEx improves the ergonomics of Java streams. The way I would implement the original example: EntryStream.of(cart.getProducts()) .mapKey(Product::getPrice) .mapValue(BigDecimal::new) .mapKeyValue(BigDecimal::multiply) .reduce(BigDecimal.ZERO, BigDecimal::add); Unfortunately BigDecimal is not especially ergonomic (it could use a `multiply(long)` method, which would eliminate the annoying `mapValue()` above). But unlike the python version of this, it will preserve scale. And streams work as-is on Money types.