Java8Lambda表达式

参考:https://www.cnblogs.com/coprince/p/8692972.html

1、使用lambda表达式替换匿名类,而实现Runnable接口是匿名类的最好示例。

     用() -> {}代码块替代了整个匿名类

// Java 8之前:
new Thread(new Runnable() {
    @Override
    public void run() {
    System.out.println("Before Java8, too much code for too little to do");
    }
}).start();

//Java 8方式:
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();

2、使用Java 8 lambda表达式进行事件处理

// Java 8之前:
JButton show =  new JButton("Show");
show.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    System.out.println("Event handling without lambda expression is boring");
    }
});

// Java 8方式:
show.addActionListener((e) -> {
    System.out.println("Light, Camera, Action !! Lambda expressions Rocks");
});

3、使用lambda表达式对列表进行迭代

// Java 8之前:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
for (String feature : features) {
    System.out.println(feature);
}

// Java 8之后:
List features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
features.forEach(n -> System.out.println(n));

4、Java 8中使用lambda表达式的Map和Reduce示例

    

// 为每个订单加上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);

5、通过过滤创建一个String列表

//流提供了一个 filter() 方法,接受一个 Predicate 对象,即可以传入一个lambda表达式作为过滤逻辑。
private static void test3(List<String> costBeforeTax) {
    List<String> filtered = costBeforeTax.stream().filter(x -> x.length()> 2).collect(Collectors.toList());
    filtered.stream().map(str -> str).forEach(System.out::println);
}

版权声明:本文为zy1104560031原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。