java - Generically-typed interface for which lambdas can be used? -
i'm still new lambda expressions, , i've been trying practice them in order better understand how work. came across pdf online few exercises practice: http://www.java-programming.info/tutorial/pdf/java/exercises/exercises-lambdas-1.pdf . on last problem, , having difficulty understanding needed accomplish it.
here code have:
interface twoelementpredicate <e> { boolean bettercheck(e e1, e e2); } public class lambdapractice4 <e> { public static void main(string[] args) { car car1 = new car(50); car car2 = new car(100); employee worker1 = new employee(500, "john"); employee worker2 = new employee(1000, "tom"); string str1 = "string"; string str2 = "secondstring"; //these 3 lines not work, due duplicate variables. thought lambdas functions though? twoelementpredicate<string> betterelement = (s1, s2) -> { return s1.length() > s2.length(); }; twoelementpredicate<car> betterelement = (c1, c2) -> { return c1.getprice() > c2.getprice(); }; twoelementpredicate<employee> betterelement = (w1, w2) -> w1.getsalary() > w2.getsalary(); //trying different syntaxes /* these work, instead of different ending arguments (bettercar, betterstring, etc.) want 1 betterelement system.out.println(betterentry(car1, car2, bettercar).getprice()); system.out.println(betterentry(str1, str2, betterstring)); system.out.println(betterentry(worker1, worker2, betterworker).getname()); */ //this have replace 3 statements above system.out.println(betterentry(car1, car2, betterelement)); system.out.println(betterentry(str1, str2, betterelement)); system.out.println(betterentry(worker1, worker2, betterelement)); } public e betterentry(e e1, e e2, twoelementpredicate genericface) { return genericface.bettercheck(e1, e2) ? e1 : e2; } /* public static car betterentry(car c1, car c2, twoelementpredicate genericface) { return genericface.bettercheck(c1, c2) ? c1 : c2; } public static employee betterentry(employee e1, employee e2, twoelementpredicate genericface) { return genericface.bettercheck(e1, e2) ? e1 : e2; } public static string betterentry(string s1, string s2, twoelementpredicate genericface) { return genericface.bettercheck(s1, s2) ? s1 : s2; } */ }
the employee , car classes defined underneath code; they're not relevant issues i'm having, exist wondering.
Comments
Post a Comment