java-lambda小计

1.替代匿名内部类
替代前:

  public void oldRunable() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("The old runable now is using!");
            }
        }).start();
    }
    
 

替代后:

  public void runable() {
        new Thread(() -> System.out.println("It's a lambda function!")).start();
    }

2. 迭代访问集合

  public void iterTest() {
        List<String> languages = Arrays.asList("java","scala","python");
        //before java8
        for(String each:languages) {
            System.out.println(each);
        }
        //after java8
        languages.forEach(x -> System.out.println(x));
        languages.forEach(System.out::println);
    }

3. 实现map

public void mapTest() {
    List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
    cost.stream().map(x -> x + x*0.05).forEach(x -> System.out.println(x));

4. 实现map与reduce
非使用lambda表达式:

public void sumTest() {
    List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
    double sum = 0;
    for(double each:cost) {
        each += each * 0.05;
        sum += each;
    }
    System.out.println(sum);
}

使用lambda表达式:

public void mapReduceTest() {
    List<Double> cost = Arrays.asList(10.0, 20.0,30.0);
    double allCost = cost.stream().map(x -> x+x*0.05).reduce((sum,x) -> sum + x).get();
    System.out.println(allCost);
}

5.filter操作

 public void filterTest() {
     List<Double> cost = Arrays.asList(10.0, 20.0,30.0,40.0);
     List<Double> filteredCost = cost.stream().filter(x -> x > 25.0).collect(Collectors.toList());
     filteredCost.forEach(x -> System.out.println(x));
 }

6.与函数式接口Predicate配合

  public static void filterTest(List<String> languages, Predicate<String> condition) {
    languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));
}
public static void main(String[] args) {
    List<String> languages = Arrays.asList("Java","Python","scala","Shell","R");
    System.out.println("Language starts with J: ");
    filterTest(languages,x -> x.startsWith("J"));
    System.out.println("\nLanguage ends with a: ");
    filterTest(languages,x -> x.endsWith("a"));
    System.out.println("\nAll languages: ");
    filterTest(languages,x -> true);
    System.out.println("\nNo languages: ");
    filterTest(languages,x -> false);
    System.out.println("\nLanguage length bigger three: ");
    filterTest(languages,x -> x.length() > 4);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值