Java Tip of the Week #4 – Lambdas
This week Java Tip of the Week is the sequel to last week Streams API episode.
Lambdas is definitely one of the most awaited features in Java. Quoting Mark Reinhold – Chief Architect of Java Platform Group, Oracle:
“Lambda is the single largest upgrade to the programming model. Ever. It’s larger even than Generics. It’s the first time since the beginning of Java that we’ve done a carefully coordinated co-evolution of the virtual machine, the language and the libraries, all together. Yet the result still feels like Java.”
Java Lambdas
Lambdas is what make the new Streams API really powerful. Nothing was stopping Java to come up with a behaviour based API to perform operations on a sequence of elements. But who wants to code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | items.stream() .map(new Function<Object, Auction>() { @Override public Auction apply(Object o) { return (Auction) o; } }) .filter(new Predicate<Auction>() { @Override public boolean test(Auction auction) { return auction.getBuyout() > 100; } }) .forEach(new Consumer<Auction>() { @Override public void accept(Auction auction) { em.persist(auction); } }); |
When you can code like this:
1 2 3 4 | items.stream() .map(o -> (Auction) o) .filter(a -> a.getBuyout() > 100) .forEach(em::persist); |
Check it out in my video:
Remember to follow my Youtube channel for faster updates!
Leave a comment if you enjoyed it, if not leave one as well!