EP09 – Java 8 – Lambda Expressions смотреть онлайн
Check out more great lessons via this link:
http://coderscampus.com/blog
With the release of Java’s version 8 back in 2014, it has quickly become the
most quickly adopted Java version to date.
Why are people so excited about it?
Well there are some pretty neat new “toys” we can play around with.
One such “toy” are lambda expressions. Though they may seem complex, I’ll try my
best to break them down and make them as simple as possible.
Benefits of the Lambda Expression
From what I can tell, there’s really only one big advantage to using a Lambda
expression…
Less code to write!
I’ll explain what I mean with an example.
Let’s consider the compare() method, which is used as part of the Comparator
interface.
We typically see the Comparator used as an anonymous inner class, and anonymous
inner classes are notorious for a lot of “noise”.
Let’s assume we have a list of Transactions that need to be sorted by their
date. How would we accomplish this without Lambas?
List transactions = getTransactionsFromDB();
Collections.sort(transactions, new Comparator()
{
@Override
public int compare(Transaction t1, Transaction t2)
{
return t1.getDate().compareTo(t2.getDate());
}
});
Now let’s take a look at how we can make this less verbose with Lambdas:
List transactions = getTransactionsFromDB();
Collections.sort(transactions, (Transaction t1, Transaction t2) -
t1.getDate().compareTo(t2.getDate()));
A lot less code right?
Much less… but with less code comes a bit less clarity sometimes as to what’s
actually going on. So let’s talk syntax.
The Lambda Syntax
The lambda is represented by the arrow - syntax.
Arguments go on the left of the arrow and the body of the expression goes on the
right.
In our example above, the arguments are Transaction t1, Transaction t2.
The body of the expression is t1.getDate().compareTo(t2.getDate()).
But how does Java know what to do given that there seems to be a lack of
information for it to execute on?
Here’s how Java works its magic… When you’re executing the Collections.sort()
method, the second argument that it expects is a Comparator.
The Comparator is an interface that defines one method that takes two templated
parameters (in our case the templated parameters are Transaction t1 and
Transaction t2)
So, this means that since Java knows that you should inserting a Comparator as
the second parameter of the Collections.sort() method, it has some sort of idea
as to what method you could be implementing.
Then when you insert our two Transaction arguments to the left of the Lambda
syntax, Java knows that you must want to use the compare method.
I think of it like method overloading. When you have a bunch of methods that all
share the exact same name, but they all have different method signatures… Java
knows which method to invoke based on the arguments you pass in to the method.
The same concept is happening here, it’s using the method signatures to figure
out which of the interface’s methods you’d like to invoke.
Then, since this is an interface after all, there’s no body in the interface’s
method… so we need to give it some code! This is the code that we include to the
right of the Lambda’s arrow syntax.
Java can then put all the pieces together and re-create the more verbose
anonymous inner class code and your program will work just as well as it did
before.
Further Shortening of Lambda Code
One more thing that you can do to shorten your Lambda expression code is to
remove the parameter types for the parameters to the left of the arrow syntax.
Java will be able to infer the data types in most cases, so they can almost
always be omitted.
Let’s revisit our sorting code from before and remove the data types:
List transactions = getTransactionsFromDB();
Collections.sort(transactions, (t1, t2) -
t1.getDate().compareTo(t2.getDate()));
Do you see how it now just says (t1, t2) instead of (Transaction t1, Transaction
t2)?
That’s more Java 8 magic at work. Java knows that the (t1, t2) variables should
be of type Transaction.
Pretty cool
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «EP09 – Java 8 – Lambda Expressions» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.