Understanding when and how to use Java 8 Lambdas

后端 未结 1 1785
不思量自难忘°
不思量自难忘° 2020-12-30 04:37

I have been spending some time trying to learn some of Java 8\'s new features. As an exercise, I wrote a MergeSort using some Java 8 Functional Interfaces. I\'m including

相关标签:
1条回答
  • 2020-12-30 05:44

    The idea of lambda expressions is that instead of creating a class that implements a functional interface, you can define a lambda expression of the type of that interface.

    For example, your Merge class implements BinaryOperator<int[]> and can be replaced by the following lambda expression :

    BinaryOperator<int[]> merge = (t,u) -> {
        int[] result = new int[t.length + u.length];
        for (int i = 0, j = 0, k = 0; i < result.length; i++){
            if( j == t.length){
                result[i] = u[k++];
            } else if (k == u.length) {
                result[i] = t[j++];
            } else {
                result[i] = t[j] < u [k] ? t[j++] : u[k++];
            }
        }
        return result;
    };
    

    Now we can similarly create a lambda expression to replace the MergeSort class, and, combining the two lambdas, we get :

    public class MergeSortMain {
        public static Function<int[], int[]> mergeSort;
        public static void main(String[] args) {
            int values[] = {3,12,6,7,2,1,23,4,5,7,8,4,2,5,365};
            mergeSort = l -> {
                BinaryOperator<int[]> merge = (t,u) -> {
                    int[] result = new int[t.length + u.length];
                    for (int i = 0, j = 0, k = 0; i < result.length; i++){
                        if( j == t.length){
                            result[i] = u[k++];
                        } else if (k == u.length) {
                            result[i] = t[j++];
                        } else {
                            result[i] = t[j] < u [k] ? t[j++] : u[k++];
                        }
                    }
                    return result;
                };
                if(l.length <= 1){
                    return l;
                }
                return merge.apply( mergeSort.apply(Arrays.copyOfRange(l, 0, l.length / 2)), 
                                    mergeSort.apply(Arrays.copyOfRange(l, l.length / 2, l.length )));
            };
            System.out.println(Arrays.toString(mergeSort.apply(values)));
        }
    }
    

    Some points regarding this code :

    1. I had to rename the parameter of mergeSort lambda from t to l, since t is also used in the merge lambda.
    2. I had to declare the mergeSort lambda as a static member (prior to assigning its value), since it contains recursive calls to itself.
    0 讨论(0)
提交回复
热议问题