In: Computer Science
You are given the following class definition (assume all methods are correctly implemented):
public class Song {
...
public Song(String name, String artist) { ... }
public String getName() { ... }
public String getArtist() { ... }
public String getGenre() { ... }
public int copiesSold() { ... }
}
Write NAMED and TYPED lambda expressions for each of the following,
using appropriate functional interfaces from the java.util.function
and java.util packages (Only the lambda expression with no
type+name will get max half credit):
Question:
A predicate for songs that are not of the genre "Pop" or "Rock", and have sold 10,000 or more copies. You may write named and typed supporting predicates, if needed.
Java Lambda code
Java Lambda Code to create a Predicate for songs
Name and typed supporting predicates:
//equalToPop supporting predicate to check if genre is equal to Pop
Predicate<Song> equalToPop = (i) -> i.getGenre() == "Pop";
//equalToRock supporting predicate to check if genre is equal to Rock
Predicate<Song> equalToRock = (i) -> i.getGenre() == "Rock";
//copiesMoreThanTenThousand supporting predicate to check if copies sold is 10,000 or more
Predicate<Song> copiesMoreThanTenThousand = (i) -> i.copiesSold() >= 10000;
Predicate for the main condition:
/*predicate that combines all the supporting predicates for songs that are not of the genre
"Pop" or "Rock", and have sold 10,000 or more copies*/
boolean res=((equalToPop.or(equalToRock)).negate()).and(copiesMoreThanTenThousand).test(obj);
Sample code to test the predicate:
Sample output: