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

OtherUsedCaseOfLambda.displayWatchAnime2(animeList,
(Anime anime) -> anime.watchedTimes >= 2 &&
anime.watchedTimes <= 10 &&
anime.animeGenre.equals("comedy"),
(Anime anime) -> anime.displayWatchAnime(anime));
}
}
class Anime{
String animeName;
int watchedTimes;
String animeGenre;

public Anime(String name, int times, String genre){
animeName = name;
watchedTimes = times;
animeGenre = genre.toLowerCase();
}
public void displayWatchAnime(Anime anime){
System.out.println(anime.animeGenre + " " + anime.animeName + ": " + anime.watchedTimes);

}
}

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

Result:

comedy Recreators: 5

Another example, this time with a return type.

interface Function<T, R>{

    R apply(T t);

}

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

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
class OtherUsedCaseOfLambda {

public static void displayWatchAnime2(
List<Anime> list,
Predicate<Anime> criteria,
Function<Anime, String> mapping,
Consumer<String> display){

for(Anime anime: list) {
if (criteria.test(anime)) {
String result = mapping.apply(anime);
display.accept(result);
}
}
}

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

OtherUsedCaseOfLambda.displayWatchAnime2(animeList,
(Anime anime) -> anime.watchedTimes >= 2 &&
anime.watchedTimes <= 10 &&
anime.animeGenre.equals("comedy"),
(Anime anime) -> anime.getAnimeName(),
(String str) -> System.out.println(str));
}
}
class Anime{
String animeName;
int watchedTimes;
String animeGenre;

public Anime(String name, int times, String genre){
animeName = name;
watchedTimes = times;
animeGenre = genre.toLowerCase();
}
public String getAnimeName(){
return animeName;
}

}

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

Result:

Recreators

In the Function interface, it has two data type which are two objects (Anime and String). Anime object was used as a parameter to its method apply() and the String was the return type of that method. 

8. Used generics more extensively

    You have seen what a generics is. like this standard function: 

interface Function<T, R>{

    R apply(T t);

}

Java ProgrammingWhere stories live. Discover now