JDK1.8之Lambda练习

一:Lambda表达式格式及说明

Lambda表达式的标准格式为: (参数类型 参数名称) ‐> { 代码语句 }
说明:

  • 小括号内的语法与传统方法参数列表一致
  • -> 是新引入的语法格式,代表指向动作 ,表示小括号前面的参数被用于后面{}里面的代码语句
  • 大括号内的语法与传统方法体要求基本一致,它实际上是对函数式接口里唯一的那个抽象方法的重写

二:Lambda省略格式

Lambda强调的是“做什么”而不是“怎么做”,所以凡是可以根据上下文推导得知的信息,都可以省略。
省略规则如下:

  • 小括号内参数的类型可以省略;
  • 如果小括号内有且仅有一个参,则小括号可以省略;
  • 如果大括号内有且仅有一个语句,则无论是否有返回值,都可以省略大括号、return关键字及语句分号。

1、Lambda练习

1.1、调用Collections.sort()方法,通过定制排序比较两个Employee(先按年龄比,年龄相同按照姓名比),使用Lambda作为参数传递
参考代码如下:

package com.demo.lambda.day04;

public class Employee {
    private String name;
    private  int age;

    /**
     * 有参构造
     * @param name
     * @param age
     */
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

}
package com.demo.lambda.day04;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 调用Collections.sort()方法,
 * 通过定制排序比较两个Employee(先按年龄比,年龄相同按照姓名比),
 * 使用Lambda作为参数传递
 */
public class lambdaCompareAge {
    public static void main(String[] args) {
        List<Employee> list = Arrays.asList(new Employee("小红", 13),
                new Employee("小明", 11),
                new Employee("小张", 12),
                new Employee("小李", 11));
        Collections.sort(list,(e1,e2)->{
            int num1 = Integer.compare(e1.getAge(), e2.getAge());
            int num2 = num1==0?e1.getName().compareTo(e2.getName()):num1;
            return num2;
        });
        //遍历循环输出
        for(Employee e:list){
            System.out.println(e);
        }
    }
}

1.2、声明函数式接口,接口中声明抽象方法public String getValue(String str)
声明类Test02,类中编写方法使用接口作为参数,将一个字符串转成大写,并作为方法的返回值
再将一个字符串的第2个到第4个索引位置的元素进行截取
参考代码如下:

package com.demo.lambda.day04;

@FunctionalInterface
public interface StringInter {
    public String getValue(String str);
}
package com.demo.lambda.day04;

public class StringLambdaTest {
    public static void main(String[] args) {
        String str = "HelloWorld";
        //需求1:将一个字符串转成大写
        String s1 = fun(str, s->s.toUpperCase());
        System.out.println(s1);

        //需求2:将一个字符串的第2个和第4个索引位置进行截取子串
        String s2 = fun(str, s->s.substring(2, 5));
        System.out.println(s2);
    }

    //用于处理字符串
    public static String fun(String s,StringInter i){
        return i.getValue(s);
    }
}

1.4、String str = “赵丽颖,28”;
将字符串截取数字年龄部分,得到字符串;
将上一步的字符串转换成为int类型的数字;
将上一步的int数字加100,得到结果int数字。
参考代码如下:

package com.demo.lambda.day04;

import org.junit.Test;
import java.util.function.Function;

public class Demo4 {
    @Test
    public void test04() {
        String str = "赵丽颖,28";
        int result = fun(s->s.split(",")[1],
                s->Integer.parseInt(s), 
                n -> n += 100, str);
        System.out.println(result);
    }

    public int fun(Function<String,String> one,
                   Function<String,Integer> two, Function<Integer,Integer> three, String s){
        return one.andThen(two).andThen(three).apply(s);
    }
}

1.5、请按照格式“ 姓名:XX。性别:XX。 ”的格式将信息打印出来。
“迪丽热巴,女”,“古力娜扎,女”,“努尔哈赤,男”
参考代码如下:

package com.demo.lambda.day04;

import org.junit.Test;

import java.util.function.Consumer;

public class Demo5 {
    @Test
    public void test05() {
        String[] arr = {"迪丽热巴,女","古力娜扎,女","努尔哈赤,男"};
        printInfo(s->System.out.print("姓名:"+s.split(",")[0]),
                s->System.out.println("。性别:"+s.split(",")[1]), arr);
    }

    public void printInfo(Consumer<String> one, Consumer<String> two, String[] arr){
        for(String s:arr){
            one.andThen(two).accept(s);
        }
    }
}
==========================
输出结果:
姓名:迪丽热巴。性别:女
姓名:古力娜扎。性别:女
姓名:努尔哈赤。性别:男

1.6、数组当中有多条“姓名+性别”的信息(“迪丽热巴,女”,“古力娜扎,女”,“努尔哈赤,男”,“赵丽颖,女”)
请通过 Predicate 接口的拼装将符合要求的字符串筛选到集合ArrayList 中,需要同时满足两个条件:
1)必须为女生;2)姓名为4个字
参考代码如下:

package com.demo.lambda.day04;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class Demo6 {
    @Test
    public void test06() {
        String[] ary = {"迪丽热巴,女","古力娜扎,女","努尔哈赤,男","赵丽颖,女"};
        List<String> list = filter(s->s.split(",")[1].equals("女"),
                s->s.split(",")[0].length()==4, ary);
        System.out.println(list);
    }

    public List<String> filter(Predicate<String> one, Predicate<String> two, String[] ary){
        List<String> list = new ArrayList<String>();
        for(String p:ary){
            if(one.and(two).test(p)){
                list.add(p.split(",")[0]);
            }
        }
        return list;
    }

}
输出结果:
[迪丽热巴, 古力娜扎]

猜你喜欢

转载自blog.csdn.net/qq_30764991/article/details/113063514