lambda表达式和函数式接口

该博客围绕Java8展开,重点介绍了Lambda表达式,包括其作为匿名函数的概念、应用场景、多种语法格式,还指出其需要函数式接口支持。同时阐述了函数式接口的定义,以及Java8内置的消费型、供给型、函数型、断言型四大核心函数式接口。

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

1 Lambda 表达式
1.1 lambda是一个匿名函数

原先的匿名内部类

//例如 比较器 
Comparator<String> com = new Comparator<String>(){
   @Override
     public int compare(String o1, String o2) {
         return Integer.compare(o1.length(), o2.length());
     }
 };
 
TreeSet<String> ts = new TreeSet<>(com);

TreeSet<String> ts2 = new TreeSet<>(new Comparator<String>(){
@Override
	public int compare(String o1, String o2) {
		return Integer.compare(o1.length(), o2.length());
	}
	
});

//现在的 (使用Lambda 表达式)

public void test2(){
	Comparator<String> com = (x, y) -> Integer.compare(x.length(), y.length());
	TreeSet<String> ts = new TreeSet<>(com);
}
1.2 lambda应用

集合

List<Employee> emps = Arrays.asList(
            new Employee(101, "张三", 18, 9999.99),
            new Employee(102, "李四", 59, 6666.66),
            new Employee(103, "王五", 28, 3333.33),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
    );

    //需求:获取公司中年龄小于 35 的员工信息
    public List<Employee> filterEmployeeAge(List<Employee> emps){
        List<Employee> list = new ArrayList<>();

        for (Employee emp : emps) {
            if(emp.getAge() <= 35){
                list.add(emp);
            }
        }

        return list;
    }
    //需求:获取公司中工资大于 5000 的员工信息
    public List<Employee> filterEmployeeSalary(List<Employee> emps){
        List<Employee> list = new ArrayList<>();

        for (Employee emp : emps) {
            if(emp.getSalary() >= 5000){
                list.add(emp);
            }
        }

        return list;
    }

优化方式1:策略模式 - 匿名内部类
策略类

public interface MyPredicate<T> {
	public boolean test(T t);
	
}

//公共方法
public List<Employee> filterEmployee(List<Employee> emps, MyPredicate<Employee> mp){
		List<Employee> list = new ArrayList<>();
		
		for (Employee employee : emps) {
			if(mp.test(employee)){
				list.add(employee);
			}
		}
		
		return list;
}
	
public void test5(){
		List<Employee> list = filterEmployee(emps, new MyPredicate<Employee>() {
			@Override
			public boolean test(Employee t) {
				return t.getAge() <= 35;
			}
		});
		
		for (Employee employee : list) {
			System.out.println(employee);
		}
	}	

在这里插入图片描述
优化方式2: lamada表达式

public static void test6(List emps){
      List<Employee> list = filterEmployee(emps, (e) -> e.getAge() <= 35);
       list.forEach(System.out::println);

       System.out.println("------------------------------------------");

       List<Employee> list2 = filterEmployee(emps, (e) -> e.getSalary() >= 5000);
       list2.forEach(System.out::println);
  }

优化方式3:Stream API

public static void test7(List<Employee> emps){
      emps.stream()
               .filter((e) -> e.getAge() <= 35)
               .forEach(System.out::println);

       System.out.println("----------------------------------------------");

       emps.stream()
               .map(Employee::getName)
               .limit(2)//取前两个
              //.sorted()
               .forEach(System.out::println);
   }
    test7(emps);

在这里插入图片描述

1.3 lambda 语法

语法格式一:接口方法 无参数,无返回值

  •  () -> System.out.println("Hello Lambda!");
    
	Runnable r = new Runnable() {
			@Override
			public void run() {
				System.out.println("Hello World!" + num);
			}
		};
		
		r.run();
		
		System.out.println("-------------------------------");
		
		Runnable r1 = () -> System.out.println("Hello Lambda!");
		r1.run();

语法格式二:有一个参数,并且无返回值

  •  (x) -> System.out.println(x)
    
	 public void test2(){
	    //java 自带类
		Consumer<String> con = (x) -> System.out.println(x);
		con.accept("德玛西亚!");
	}

在这里插入图片描述
语法格式三:若只有一个参数,小括号可以省略不写

  •  x -> System.out.println(x)
    
 public void test2(){
	    //java 自带类
		Consumer<String> con = x -> System.out.println(x);
		con.accept("德玛西亚!");
  }

语法格式四:有两个以上的参数,有返回值,并且 Lambda 体中有多条语句
Comparator com = (x, y) -> {
System.out.println(“函数式接口”);
return Integer.compare(x, y);
};
在这里插入图片描述

public void test3(){
		Comparator<Integer> com = (x, y) -> {
			System.out.println("函数式接口");
			return Integer.compare(x, y);
		};
	}

语法格式五:若 Lambda 体中只有一条语句, return 和 大括号都可以省略不写

  •  Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
    
public void test4(){
		Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
	}

语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”

  •  (Integer x, Integer y) -> Integer.compare(x, y);
    
1.4 Lambda 表达式需要“函数式接口”的支持
  • 函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。 可以使用注解 @FunctionalInterface 修饰 修饰完只能有一个抽象方法

练习
先按年龄比 ,年龄一样按姓名比在这里插入图片描述
return 负号在这里插入图片描述

2 函数式接口
public interface MyFunc<T,R> {
    public R getVVV(T t1, T t2) ;
}
public class Test2 {
    //对两long数据处理
    public  static  void  op(Long one,Long two,MyFunc<Long,Long> myFunc) {
        System.out.println(myFunc.getVVV(one,two));
    }
    public static void main(String[] args) {
        op(100L, 200L, (x, y) -> x + y);
        op(100L, 200L, (x, y) -> x * y);
    }
}

3 Java8 内置的四大核心函数式接口
/
 * Consumer<T> : 消费型接口
 * 		void accept(T t);
 * 
 * Supplier<T> : 供给型接口
 * 		T get(); 
 * 
 * Function<T, R> : 函数型接口
 * 		R apply(T t);
 * 
 * Predicate<T> : 断言型接口
 * 		boolean test(T t);
 * 
 */

消费型接口

//Consumer<T> 消费型接口 :
	public void test1(){
		happy(10000, (m) -> System.out.println("你们刚哥喜欢大宝剑,每次消费:" + m + "元"));
	} 
	
	public void happy(double money, Consumer<Double> con){
		con.accept(money);
	}

供给型接口

//Supplier<T> 供给型接口 :
	public void test2(){
		List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
		
		for (Integer num : numList) {
			System.out.println(num);
		}
	}
	
	//需求:产生指定个数的整数,并放入集合中
	public List<Integer> getNumList(int num, Supplier<Integer> sup){
		List<Integer> list = new ArrayList<>();
		
		for (int i = 0; i < num; i++) {
			Integer n = sup.get();
			list.add(n);
		}
		
		return list;
	}

函数型接口

//Function<T, R> 函数型接口:
	public void test3(){
		String newStr = strHandler("\t\t\t 我德玛西亚   ", (str) -> str.trim());
		System.out.println(newStr);
		
		String subStr = strHandler("我大盖伦", (str) -> str.substring(2, 5));
		System.out.println(subStr);
	}
	
	//需求:用于处理字符串
	public String strHandler(String str, Function<String, String> fun){
		return fun.apply(str);
	}

断言型接口

	//Predicate<T> 断言型接口:
	public void test4(){
		List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
		List<String> strList = filterStr(list, (s) -> s.length() > 3);
		
		for (String str : strList) {
			System.out.println(str);
		}
	}
	
	//需求:将满足条件的字符串,放入集合中
	public List<String> filterStr(List<String> list, Predicate<String> pre){
		List<String> strList = new ArrayList<>();
		
		for (String str : list) {
			if(pre.test(str)){
				strList.add(str);
			}
		}
		
		return strList;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值