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.
5
u/calmonad Mar 30 '20
JavaBrains has a pretty good lambda basics playlist: https://www.youtube.com/playlist?list=PLqq-6Pq4lTTa9YGfyhyW2CqdtW9RtY-I3
I also like Venkat Subramaniam's talks on the subject.
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
List<Integer> SortIntegerListAcending(List<Integer> list){
//code
//is element a < b?
}
List<Integer> SortIntegerListDescending(List<Integer> list){
//same code
// is element a > b?
} 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:
List<Integer> SortIntegerList(List<Integer> list, Comparator<Integer> comparator){
//code
// comparator.comparare(a,b)
} 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
foo(){
List<Integer> myList...
//sorts by acending
MySorter.sortIntegerList(myList, new Comparator(){
public boolean compare(Integer a, Integer b){
return a < b;
}
})
MySorter.sortIntegerList(myList, new Comparator(){
public boolean compare(Integer a, Integer b){
return a > b;
}
})
}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
foo(){
List<Integer> myList...
//sorts by acending
MySorter.sortIntegerList(myList, (a,b) -> {return a< b;})
MySorter.sortIntegerList(myList, (a,b) -> {return a>b;}))
//since there's only one line the return parameter you can shorten it to (a,b)-> a<b
}1
Mar 31 '20
What is your experience level with Java so far? Lambda expressions can be difficult to grasp without some other prior experience (such as with implementing interfaces) and isn't necessary for you to use or understand right away when you are learning Java
0
u/RexStardust Mar 30 '20
Here's an example from a little side project:
List <Transaction> returnDetailList = transactionArray.stream() .filter(x -> (x.getStatustext().equals(transactionType))) .filter(x -> (x.getTransactionCompleteTime().toLocalDate().isAfter(transactionRange.getAfterStartDate()))) .filter(x -> (x.getTransactionCompleteTime().toLocalDate().isBefore(transactionRange.getBeforeEndDate()))) .collect(Collectors.toList());
This takes an array of Transaction objects (Blue Prism robotics), filters by transaction type (completed or exception), then further filters to select transactions in the given date range. The output of the stream is a List of Transaction objects.
3
u/BananaPunsch Mar 30 '20
Thanks. I think I found a site that explains Lambdas with some easy examples. I appreciate the effort, I was just searching for an easy explantation so I could understand why I would use a Lambda instead of just implementing the full interface. By using Lambdas it seems like I don't have to implement a interface in the normal way. I basically use the interface to provide a head for a method and use the Lambda to complete the method. I just needed a easy visual of picture how everything is connected.
3
u/AnotherThrowAway_9 Mar 30 '20
If you have a functional interface you can use a lambda. Lambdas reduce the amount of code that you have to write.
Thread t = new Thread( () -> { myObject.func() } );
That’s much shorter than writing the code into the runnable() method.
You can also do this with actionlisteners for the actionPerformed() method.
So you can use them in places when you write “implements AnInterfaceHere”