可以使用lambdas的通用类型接口?

时间:2016-11-05 19:12:35

标签: java lambda

我还是lambda表达式的新手,我一直在努力练习它们,以便更好地理解它们的工作原理。我在网上看到了一些pdf练习:http://www.java-programming.info/tutorial/pdf/java/exercises/exercises-lambdas-1.pdf。我是最后一个问题,我很难理解完成它需要什么。

以下是我目前的代码:

    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 three lines do not work, due to duplicate variables. I thought lambdas were 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, but instead of different ending arguments (betterCar, betterString, etc.) I want just one 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 is what I would like to have to replace the three 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;
    }
    */
}

Employee和Car类在此代码下定义;它们与我所遇到的问题并不紧密相关,但它们确实适用于那些想知道的人。

0 个答案:

没有答案