189 8069 5689

Lambda表达式的说明和实例用法

本篇内容介绍了“Lambda表达式的说明和实例用法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

专注于为中小企业提供做网站、成都网站设计服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业当阳免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

Lambda表达式,一种简单的匿名内部类(但是只能对应  只有一个抽象方法的接口-->函数式接口)

- 举例

  - 无参  基础运用

    ```java

    interface InterfaceA{

        public void show();

    }

    public class Demo1 {

        public static void main(String[] args) {

            //匿名内部类

            InterfaceA a = new InterfaceA() {

                public void show() {

                    System.out.println("匿名内部类的show");

                }

            };

            a.show();

            //通过lambda表达式

            InterfaceA b = ()->{

                System.out.println("lambda表达式的show");

            };

            b.show();

            //简化

            InterfaceA bb = ()->System.out.println("简化的lambda表达式的show");

            bb.show();

        }

    }

    ```

  - 带参数 基础运用

    ```java

    interface A{

        public int add(int i,int j);

    }

    class B{

        public int bAdd(int i,int j){

            return i+j;

        }

    }

    public class Lambda {

        public static void main(String[] args) {

            //lambda表达式需要返回值,而它的代码块中仅有一条省略了return的语句

            //lambda表达式会自动返回这条语句的结果

            //A a=(i,j)->{return i+j;};   

            A a=(i,j)->i+j; //基础用法,这就很类似匿名内部类了

            System.out.println(a.add(4,5));

        }

    }

    interface A{

        public int add(int i,int j);

    }

    class B{

        public int bAdd(int i,int j){

            return i+j;

        }

    }

    public class Lambda {

        public static void main(String[] args) {

            A a=new B().bAdd();//思想参考 C#  委托

            System.out.println(a.add(4,5));

        }

    }

    interface A{

        public int add(int i,int j);

    }

    class B{

        //静态

        public static int bAdd(int i,int j){

            return i+j;

        }

    }

    public class Lambda {

        public static void main(String[] args) {

            //调用方式不一样了

            A a=B::bAdd;//思想参考 C#  委托

            System.out.println(a.add(4,5));

        }

    }

    ```

  - 引用类方法

    ```java

    interface Converter{

        //将字符串转换成整数

        Integer convert(String value);

    }

    class Test1{

        public static void fun1() {

            //原来的方法

            Converter converter = value->Integer.valueOf(value);

            Integer v1 = converter.convert("222");

            System.out.println(v1);

            //简化

            //引用类方法

            //通过::实现,这里会自动将lambda表达式方法的参数全部传递给当前的方法

            Converter converter2 = Integer::valueOf;

            Integer v2 = converter2.convert("333");

            System.out.println(v2);

        }

    }

    ```

  - 引用特定对象的实例方法

    ```java

    interface IA{

        public void show(String message);

    }

    class A{

        public void play(String i) {

            System.out.println("这里是A的方法play"+"  i:"+i);

        }

    }

    class Test2{

        public static void fun2() {

            //原来

            IA ia = message->new A().play(message);

            ia.show("hello");

            //简化

            IA ia2 = new A()::play;

            ia2.show("world");

        }

    }

    ```

  - 引用构造方法

    ```java

    interface IC{

        Object show(String name,int age);

    }

    class Person{

        String name;

        int age;

        public Person(String name, int age) {

            super();

            this.name = name;

            this.age = age;

        }

        @Override

        public String toString() {

            return "Person [name=" + name + ", age=" + age + "]";

        }

    }

    class Test4{

        public static void fun4() {

            IC ic = (name,age)->new Person(name, age);

            Object per = ic.show("bing", 19);

            System.out.println(per);

            //简化

            //构造方法引用代替lambda表达式,函数式接口中被实现方法的全部参数传该构造方法作为参数

            IC ic2 = Person::new;

            Object per1 = ic2.show("chen", 10);

            System.out.println(per1);

        }

    }

    ```

- 应用

```java

String[] strings={"123","456","789","赵志阳真帅"};

List lists= Arrays.asList(strings);

lists.forEach((s)-> out.println("字符串是:"+s));

lists.forEach(out::println);

```

## 集合

```java

package collection;

import java.util.ArrayList;

import java.util.Iterator;

import java.util.Objects;

class Person{

    private String name;

    private int age;

    public Person(String name, int age) {

        this.name = name;

        this.age = age;

    }

    @Override

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        return age == person.age &&

                Objects.equals(name, person.name);

    }

    public void setName(String name) {

        this.name = name;

    }

    public void setAge(int age) {

        this.age = age;

    }

    @Override

    public String toString() {

        return "Person{" +

                "name='" + name + '\'' +

                ", age=" + age +

                '}';

    }

}

public class Main {

    public static void main(String[] args) {

        ArrayList arrayList=new ArrayList<>();

        Person zs=new Person("张三",20);

        Person zs2=new Person("张三",20);//将放不进去

        Person ls=new Person("李四",30);

        Person ww=new Person("王五",40);

        //contains判断比较的是对象的equals方法。

        if(!arrayList.contains(zs)){

            arrayList.add(zs);

        }

        if(!arrayList.contains(zs2)){

            arrayList.add(zs2);

        }

        if(!arrayList.contains(ls)){

            arrayList.add(ls);

        }

        if(!arrayList.contains(ww)){

            arrayList.add(ww);

        }

        Iterator iterator=arrayList.iterator();

        while(iterator.hasNext()){

            System.out.println(iterator.next());

        }

    }

}

```

用hash相关的容器是,重写equals hashcode

treeSet还要实现Comparable接口并重写compareTo方法。或者自定义比较器Comparator

```java

public class Demo9 {

    public static void main(String[] args) {

        //创建比较器对象

        ComStrWithLength comStrWithLength = new  ComStrWithLength();

        //将比较器对象交给TreeSet

        Set set = new TreeSet<>(comStrWithLength);

         /*

          * TreeSet的add方法实现的排序,去重.通过调用元素的compareTo方法

          * String类已经实现了Comparable接口

          */

        set.add("java");

        set.add("hadoop");

        set.add("spark");

        set.add("HDFS");

        set.add("HDFS");

        set.add("Mapreduce");

        System.out.println(set);

    }

}

//创建一个比较器类

class ComStrWithLength implements Comparator{

    @Override

    public int compare(Object o1, Object o2) {

        //比较字符串的长度

        if (!(o1 instanceof String)) {

            throw new ClassCastException("类型转换错误");

        }

        if (!(o2 instanceof String)) {

            throw new ClassCastException("类型转换错误");

        }

        //向下转型

        String s1 = (String)o1;

        String s2 = (String)o2;

        //先按照长度比

        int num = s1.length()-s2.length();

        //长度相同,再按照字典顺序比

        return num==0?s1.compareTo(s2):num;

    }

}

泛型

作用:

1. 使用了泛型不再需要进行容错处理,向下转型,强制类型转换----简化代码

2. 将运行阶段的问题提前到编译阶段检查,提高了代码的安全性和编程效率

“Lambda表达式的说明和实例用法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站名称:Lambda表达式的说明和实例用法
标题网址:http://jkwzsj.com/article/gpdiec.html

其他资讯