r/learnjava • u/BananaPunsch • Mar 30 '20
Java Lambda expressions
I am a little lost as to what they are, how they work or what I can use them for.
I have no real example, just stumbled across the term and would like to understand it.
Are there understandable easy examples?
Thanks for possible help.
Edit: I found a pretty good explanation here. I just needed a easy and small example to wrap my head around this. Thanks to everyone who tried to help.
41
Upvotes
2
u/Farpafraf Mar 31 '20 edited Mar 31 '20
Imagine you're implementing an algorithm to return a sorted List<Integer> in ascending order, at a certain point you'll have to compare elements
but then you might realize you need an equivalent method to sort in descending order. If you were to rewrite the other method anew the code would probably very similar exception made for the comparison, a way to avoid duplications would be to have a generic method that can be used for both:
When you use the method you pass down a Comparator that knows the correct criteria to compare the two numbers. You could have these two comparators as different classes SmallerComparator, GreaterComparator (notice they will implement Comparator<Integer> so they need to have a boolean compare(Integeer a, Integer b) method) but that would be very wasteful and that's why you are allowed to actually implement and create an your own instance of Comparator without declaring a new Class even as a parameter. Let's say we need to sort in ascending order in some method foo
This is still pretty bad tho, since Comparator has only one method we need to implement the compiler can deduce what we are trying to do hence we we don't need to write all that garbage and can actually rewrite it as a lambda