java8-2-Lambda表达式

java8的lambda表达式:使得代码更加紧凑;修改方法的能力;更好的支持多核处理(并行处理函数和filter\map\reduce)

例子1:

java7中,list集合排序:

public static void testJava7SortList() {
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return b.compareTo(a);
            }
        });
        System.out.println(names);
    }

java8中,list集合排序:

 

    public static void testJava8SortList1() {
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
        Collections.sort(names, (String a, String b) -> {
            return b.compareTo(a);
        });
        System.out.println(names);
    }

    public static void testJava8SortList2() {
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
        Collections.sort(names, (String a, String b) -> b.compareTo(a));
        System.out.println(names);
    }

    // 只要一行代码,包含了方法体。你甚至可以连大括号对{}和return关键字都省略不要。不过这还不是最短的写法
    // Java编译器能够自动识别参数的类型,所以你就可以省略掉类型不写
    public static void testJava8SortList3() {
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
        Collections.sort(names, (a, b) -> b.compareTo(a));
        System.out.println(names);
    }

 

例子2:

Thread的处理:

public static void testJava8Thread() {
        // Java 7:
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("java7 thread");
            }
        }).start();

        // Java 8方式:
        new Thread(() -> System.out.println("java8 thread")).start();

        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

例子3:

迭代处理:

public static void testForEach() {
        // Java 7:
        List<String> features1 = Arrays.asList("a", "b", "c", "d");
        for (String feature : features1) {
            System.out.println(feature);
        }

        // Java 8:
        List<String> features2 = Arrays.asList("a", "b", "c", "d");
        features2.forEach(n -> System.out.println(n));

        // 使用Java 8的方法引用更方便,方法引用由::双冒号操作符标示,
        // 看起来像C++的作用域解析运算符
        features2.forEach(System.out::println);
    }

 

例子4:

labmda表达式和函数试接口:

java.util.function。它包含了很多类,用来支持Java的函数式编程。其中一个便是Predicate,使用 java.util.function.Predicate 函数式接口以及lambda表达式,可以向API方法添加逻辑,用更少的代码支持更多的动态行为。

public static void testLambdaFilter() {
        List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp");
         
        //查询J开头的字符串
        System.out.println("Languages which starts with J :");
        filter(languages, (str)->str.startsWith("J"));
     
        //查询出所有
        System.out.println("Print all languages :");
        filter(languages, (str)->true);
    }
    
    public static void filter(List<String> names, Predicate<String> condition) {
        for(String name: names)  {
            if(condition.test(name)) {
                System.out.println(name + " ");
            }
        }
    }
    public static void filter2(List<String> names, Predicate<String> condition) {
        names.stream().filter((name) -> (condition.test(name))).forEach((name) -> {
            System.out.println(name + " ");
        });
    }

例子5:

 函数式编程概念map

// 为每个订单加上12%的税
// 老方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double total = 0;
for (Integer cost : costBeforeTax) {
    double price = cost + .12*cost;
    total = total + price;
}
System.out.println("Total : " + total);
 
// 新方法:
List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill);

 

 

 

posted on 2018-01-15 09:04  zhaofeng555  阅读(276)  评论(0编辑  收藏  举报