Lambda class

7 0 0
                                    

Lambda was created to make anonymous class simpler. It was said that creating an anonymous class with an interface with just one method is a bit excessive since what you are trying to do is to just pass one method to another method.

Used case examples will be provided below to show the value of lambda expression

1. Create a method that searched for members that matched one characteristic

======================

import java.util.Arrays;
import java.util.List;
class PracticingLambda {

public static void displayWatchAnime(List<Anime> list, int numOfTimes){
for(Anime anime: list){
if(anime.watchedTimes > numOfTimes){
System.out.println(anime.animeName + ": " + anime.watchedTimes);
}
}

}

public static void main(String[] args){
Anime[] animeArray = {
new Anime("Danmachi", 6),
new Anime("Naruto", 3),
new Anime("Recreators", 1)
};
List<Anime> animeList = Arrays.stream(animeArray).toList();

PracticingLambda.displayWatchAnime(animeList, 2);
}
}
class Anime{
String animeName;
int watchedTimes;

public Anime(String name, int times){
animeName = name;
watchedTimes = times;
}
}

======================

Results:

Danmachi: 6Naruto: 3


In the above code, the method is displayWatchedAnime(). The members to searched are the list of Anime. And that one characteristic is the numberOfTimes you watched the anime. List was used here. It is like an array that belongs to the Collection group. A collection is an object that groups multiple elements into a single unit where you can store, retrieve or update later on.


2. Create more generalized searched method

    What they mean is to make the above code more generic to decrease the codes brittleness.

============================

import java.util.Arrays;
import java.util.List;
class PracticingLambda {

public static void displayWatchAnime(List<Anime> list, int min, int max){
for(Anime anime: list){
if(anime.watchedTimes >= min && anime.watchedTimes <= max){
System.out.println(anime.animeName + ": " + anime.watchedTimes);
}
}

}

public static void main(String[] args){
Anime[] animeArray = {
new Anime("Danmachi", 6),
new Anime("Naruto", 3),
new Anime("Recreators", 1)
};
List<Anime> animeList = Arrays.stream(animeArray).toList();

PracticingLambda.displayWatchAnime(animeList, 2, 10);
}
}
class Anime{
String animeName;
int watchedTimes;

public Anime(String name, int times){
animeName = name;
watchedTimes = times;
}
}

============================

Results:

Danmachi: 6Naruto: 3


The above highlighted code is much more generic since we did specify a much more restricted number of times to watch the anime. Take note of &&, these two ampersands only means that if all conditions were true then, it returns true.

Java ProgrammingWhere stories live. Discover now