【java笔记】lambda表达式

【java笔记】lambda表达式

介绍

带有参数的表达式,解决代码冗余的问题

举例

用匿名内部类和lambda表达式完成相同的排序问题

匿名内部类
import java.math.BigInteger;
import java.util.*;
class Son{
    private Integer age;

    private String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Son(Integer age,String name){
        this.age=age;
        this.name=name;
    }
}

public class hello {
    public static void main(String[] args) {
        List<Son> sons=new ArrayList<Son>(){
            @Override
            public String toString() {
                String string = "";
                for (Son son : this) {
                    string += son.getName() + " ";
                }
                return string;
            }
        };
        sons.add(new Son(6,"55"));
        sons.add(new Son(4,"dw"));
        sons.add(new Son(2,"dwf"));
        Collections.sort(sons, new Comparator<Son>() {
            @Override
            public int compare(Son o1, Son o2) {
                return Double.compare(o2.getAge(),o1.getAge());
            }
        });
        System.out.println(sons.toString());
    }
}

输出为

55 dw dwf 

在上例中,排序主要是通过

@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}

Comparator<T>接口中的compare(T o1, T o2)方法在本例中通过匿名类的方式实现。

lambda表达式
Collections.sort(sons, (s1,s2)->Double.compare(s1.getAge(),s2.getAge()));
为什么可以这样写?
@FunctionalInterface
public interface Comparator<T> {
    int compare(T o1, T o2);
}

@FunctionalInterface提供了函数式接口。

举一反三

以创建线程为例

public class hello {
    public static void main(String[] args) {
        Thread a=new Thread(new Runnable(){
            @Override
            public void run() {
                System.out.println("hello world");
            }
        });
        a.start();
    }
}

可以用lambda表达式改写为

public class hello {
    public static void main(String[] args) {
        Thread a=new Thread(()->{
            System.out.println("hello world");
        });
        a.start();
    }
}
@FunctionalInterface

于是我们的目光便转变到了@FunctionalInterface

@FunctionalInterface的作用就是标识一个接口为函数式接口,此时Comparator里只能有一个抽象方法,由编译器进行判定。

系统函数接口

Function:提供任意一种类型的参数,返回另外一个任意类型返回值。 R apply(T t);

Consumer:提供任意一种类型的参数,返回空值。 void accept(T t);

Supplier:参数为空,得到任意一种类型的返回值。T get();

Predicate:提供任意一种类型的参数,返回boolean返回值。boolean test(T t);

方法引用

替换函数式接口

public class hello {
    public static void main(String[] args) {
        List<String> strings=new ArrayList<String>(){
            {
                add("jjjwfwgwg");
                add("hduiwf");
                add("fwgewgweg");
            }
        };
        Collections.sort(strings, String::compareToIgnoreCase);
        System.out.println(strings);
    }
}

String::compareToIgnoreCase等同于同样效果的lambda表达式

构造器引用
public class hello {
    public static void main(String[] args) {
        List<String> stringList =Arrays.asList("wfwf","fwfwf","fwgwg");
        Stream<Son> sonStream = stringList.stream().map(Son::new);
        Son[] sons=sonStream.toArray(Son[]::new);
    }
}

输出为

[wfwf, fwfwf, fwgwg]

其中map方法值得注意

描述为

/**
     * Returns a stream consisting of the results of applying the given
     * function to the elements of this stream.
     *
     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
     * operation</a>.
     *
     * @param <R> The element type of the new stream
     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *               <a href="package-summary.html#Statelessness">stateless</a>
     *               function to apply to each element
     * @return the new stream
     */
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);

调用函数式接口

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值