Thursday 17 March 2022

Join in SQL

There are lots of nice diagrams explaining the difference between the different joins in SQL.

References

Code Project for those who Code - Visual Representation of SQL Joins
https://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

Thursday 10 March 2022

For-loops and Streams

So, I'm almost always trying to use Streams in Java.

There are only a handful of times when Streams are not a perfect fit. And most of the times, this is when there is more than one list, and you need to traverse them in sync.

So, we have different ways of doing the same thing. Let's count 'em down.

We'll use the following test setup, using the new Java Money and Currency reference implementation1 2.

Use an ordinary for-loop

This was way back when we didn't have anything better.

And let's be honest, sometimes this is all you need and it is still surprisingly readable.

Use a for-each loop

This is one of my, let us say, less perfect attempts.

It's nice that I've used the for-each construct, but too bad I've hacked an additional index to it to do what I want.

Streams!

So, my colleague at work provided me with this solution, to get away from the whole for-loop (at least, superficially, when you look deep deep down into it, it's just a for loop written as a stream.)

I has to use a reduce in the example, because one of the disadvantages here, is that it's not allowed to reassign variables inside a lambda. Variables should be effectively final.

This disadvantage is not present in for-loops.

But I've also seen some truly horrendous hacks where people started using things like AtomicInteger as a "wrapper" workaround, so they could manipulate the inside of the wrapper inside the lambda.

References

[1] Baeldung - Java Money and the Currency API
https://www.baeldung.com/java-money-and-currency
[2] JSR 354: Money and Currency API
https://jcp.org/en/jsr/detail?id=354
Medium - Experienced Developers, Use These Quirks to Create Better Java Lambdas
https://medium.com/javarevisited/experienced-developers-use-these-quirks-to-create-better-java-lambdas-4ae656148274