Java 中的箭头->运算符

Java 中的箭头->运算符,第1张

Java 中的箭头运算符

Java 中的箭头运算符用于形成 lambda 表达式。它将参数与表达式主体分开。

(parameter) -> {statement;}; // Lambda expression having arrow

Lambda 表达式可以用来代替 Java 中的匿名类,使代码更加简洁和可读。对比如下:

// 使用匿名类
Runnable r = new Runnable() {
	@Override
    public void run() {
		System.out.print("Run method");
	}
};

// 使用 ->
Runnable r = () -> System.out.print("Run method");

由于 Runnable 是单方法接口,因此很容易使用 lambda 表达式进行覆写。


箭头运算符在流 API 中的应用

.filter().forEach() 中使用 lambda 表达式来简化代码。

import java.util.ArrayList;
import java.util.stream.Stream;

class Student{
    int id;
    String name;
    int score;
    public Student(int id, String name, int score) {
        this.id = id;
        this.name = name;
        this.score = score;
    }
}

public class test{
    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student(1, "yzc", 93));
        list.add(new Student(2, "lxy", 94));
        list.add(new Student(3, "sbw", 59));
        list.add(new Student(4, "hqm", 86));

        Stream<Student> filtered_data = list.stream().filter(s -> s.score > 60);
        filtered_data.forEach(
                stu -> System.out.println(stu.name + ": " + stu.score)
        );
    }
}

在线程中使用箭头运算符
public class test{
    static int i = 0;
    public static void main(String[] args) {
        Runnable r = () -> {
            System.out.println("hello world");
            System.out.println("i: " + (++i));
        };
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/738358.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存