Java8新特性Lambda总结

本文深入探讨了Java中Lambda表达式的概念、语法及其应用。从基本的匿名函数介绍到复杂的功能,如线程使用、数组排列和类方法引用,再到list的过滤、排序和构造方法引用,全面展示了Lambda表达式的强大功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、什么是Lambda表达式

Lambda 表达式是一种匿名函数,简单地说,它是没有声明的方法,也即没有访问修饰符、返回值声明和名字。
它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使 Java 语言的表达能力得到了提升。

2、Lambda表达式的语法

基本语法: (parameters) -> expression
或者:(parameters) ->{ statements};

lambda表达式foreach性能分析

结论是:对于耗时的操作用lambda表达式的foreach循环(多线程),如数据库的IO操作,多线程充分利用CPU资源;对于不太耗时的操作使用普通for循环,比如纯CPU计算类型的操作,单线程性能更高,减少上下文切换的开销。

3、Lambda表达式示例:

//不需要参数,返回值为 5
() -> 5

//接收一个参数(数字类型),返回其2倍的值
x -> 2 * x

//接受2个参数(数字),并返回他们的差值
(x, y) -> x – y

//接收2个int型整数,返回他们的和
(int x, int y) -> x + y

//接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)

list过滤一个属性的多个值

List<Integer> ppids = Arrays.asList(75012,75014,75016,75021,75022,75023,75024);
ppids= ppids.stream().filter(e -> e != 75012 && e != 75014 && e != 75016).collect(Collectors.toList());
System.out.println(ppids.toString());

list输出

public class TestArray {
    
    public static void main(String[] args) {
         List<String> list = Arrays.asList("xuxiaoxiao", "xudada", "xuzhongzhong");
           list.forEach(value -> System.out.println(value));
    }
    /* 输出:
     * xuxiaoxiao
     * xudada
     * xuzhongzhong
     */
}

线程使用

public class Test {
    
    public static void main(String[] args) {
        
        // 1.1使用匿名内部类  
        new Thread(new Runnable() {  
            @Override  
            public void run() {  
                System.out.println("Hello world !");  
            }  
        }).start();  
          
        // 1.2使用 lambda 获得Runnable接口对象  
        new Thread(() -> System.out.println("Hello world !")).start();  
        

        
        // 2.1使用匿名内部类  
        Runnable race1 = new Runnable() {  
            @Override  
            public void run() {  
                System.out.println("Hello world !");  
            }  
        };  
          
        // 2.2使用 lambda直接获得接口对象 
        Runnable race2 = () -> System.out.println("Hello world !");          
        
        // 直接调用 run 方法(没开新线程哦!)  
        race1.run();  
        race2.run();  
    }
}

/*输出结果

  • Hello world !
  • Hello world !
  • Hello world !
  • Hello world !
    */

数组排列

public class TestArray {
    
    public static void main(String[] args) {
        String[] players = {"zhansgan", "lisi", "wangwu", "zhaoliu",  "wangmazi"};  

        // 1.1 使用匿名内部类根据 surname 排序 players  
        Arrays.sort(players, new Comparator<String>() {  
            @Override  
            public int compare(String s1, String s2) {  
                return (s1.compareTo(s2));  
            }  
        });  
        
        // 1.2 使用 lambda 排序,根据 surname  
        Arrays.sort(players, (String s1, String s2) ->  s1.compareTo(s2));  
         
//===========================================================
          
        // 2.1 使用匿名内部类根据 name lenght 排序 players  
        Arrays.sort(players, new Comparator<String>() {  
            @Override  
            public int compare(String s1, String s2) {  
                return (s1.length() - s2.length());  
            }  
        });  

        // 2.2使用Lambda,根据name length  
        Arrays.sort(players, (String s1, String s2) -> (s1.length() - s2.length()));  
    
//=================================================================================
        
        // 3.1 使用匿名内部类排序 players, 根据最后一个字母  
        Arrays.sort(players, new Comparator<String>() {  
            @Override  
            public int compare(String s1, String s2) {  
                return (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1));  
            }  
        });  

        // 3.2 使用Lambda,根据最后一个字母
        Arrays.sort(players, (String s1, String s2) -> (s1.charAt(s1.length() - 1) - s2.charAt(s2.length() - 1)));  
    }
}

类方法引用

public class Apple {

    private String name;
    private String color;
    private double weight;

    public Apple(String name, String color, double weight) {
        this.name = name;
        this.color = color;
        this.weight = weight;
    }

    public static int compareByWeight(Apple a1, Apple a2) {
        double diff = a1.getWeight() - a2.getWeight();
        return new Double(diff).intValue();
    }

    //还有getter setter toString
}
public class LambdaTest {

    public static void main(String[] args) {

        Apple apple1 = new Apple("红富士", "Red", 280);
        Apple apple2 = new Apple("冯心", "Yello", 470);
        Apple apple3 = new Apple("大牛", "Red", 320);
        Apple apple4 = new Apple("小小", "Green", 300);

        List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4);

        //lambda 表达式形式
        //appleList.sort((Apple a1, Apple a2) -> {
        //    return new Double(a1.getWeight() - a2.getWeight()).intValue();
        //});

        //静态方法引用形式(可以看出引用方法比上面的更加简单
        appleList.sort(Apple::compareByWeight);

        appleList.forEach(apple -> System.out.println(apple));

    }
}

输出:
Apple{category=‘红富士’, color=‘Red’, weight=280.0}
Apple{category=‘小小’, color=‘Green’, weight=300.0}
Apple{category=‘大牛’, color=‘Red’, weight=320.0}
Apple{category=‘冯心’, color=‘Yello’, weight=470.0}

list排序

public class AppleComparator {

    public int compareByWeight(Apple a1, Apple a2) {
        double diff = a1.getWeight() - a2.getWeight();
        return new Double(diff).intValue();
    }
}


public class LambdaTest {

    public static void main(String[] args) {

        Apple apple1 = new Apple("红富士", "Red", 280);
        Apple apple2 = new Apple("冯心", "Yello", 470);
        Apple apple3 = new Apple("哈哈", "Red", 320);
        Apple apple4 = new Apple("小小", "Green", 300);


        List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4);

        //lambda 表达式形式
        //appleList.sort((Apple a1, Apple a2) -> {
        //    return new Double(a1.getWeight() - a2.getWeight()).intValue();
        //});

        //实例方法引用
        AppleComparator comparator = new AppleComparator();
        appleList.sort(comparator::compareByWeight);

        appleList.forEach(apple -> System.out.println(apple));

    }
}

输出:
Apple{category=‘红富士’, color=‘Red’, weight=280.0}
Apple{category=‘小小’, color=‘Green’, weight=300.0}
Apple{category=‘哈哈’, color=‘Red’, weight=320.0}
Apple{category=‘冯心’, color=‘Yello’, weight=470.0}

list排序

public class LambdaTest {

    public static void main(String[] args) {

        Apple apple1 = new Apple("红富士", "Red", 280);
        Apple apple2 = new Apple("黄元帅", "Yello", 470);
        Apple apple3 = new Apple("红将军", "Red", 320);
        Apple apple4 = new Apple("国光", "Green", 300);


        List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4);

        //lambda 表达式形式
        //appleList.sort((Apple a1, Apple a2) -> {
        //    return new Double(a1.getWeight() - a2.getWeight()).intValue();
        //});

        //这里是类方法引用
        appleList.sort(Apple::compareByWeight);

        appleList.forEach(apple -> System.out.println(apple));

    }
}

输出:
Apple{category=‘红富士’, color=‘Red’, weight=280.0}
Apple{category=‘国光’, color=‘Green’, weight=300.0}
Apple{category=‘红将军’, color=‘Red’, weight=320.0}
Apple{category=‘黄元帅’, color=‘Yello’, weight=470.0}

构造方法引用

public class ConstructionMethodTest {

    public String getString(Supplier<String> supplier) {
        return supplier.get();
    }

    public static void main(String[] args) {

        ConstructionMethodTest test = new ConstructionMethodTest();

        //lambda表达式形式
        System.out.println(test.getString(() -> { return new String();}));

        //构造方法引用形式
        System.out.println(test.getString(String::new));

    }
}

getString 方法接收一个Supplier类型的参数,Supplier 不接收参数,返回一个String。lambda表达式应该这样写:
() -> { return new String();}
替换成方法引用的形式如下: 实际上调用的是String 无参构造方法。
String::new

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值