lambda表达式的一些实现代码

四种函数型接口实现代码:

Consumer:

public class TestConsumer {

    public static void main(String[] args) {
        Consumer<String> c = (e)->System.out.println("今天天气:" + e);
        c.accept("多云");
        
        m("晴天", e-> System.out.println("今天天气:" + e));
    }
    public static void m(String s , Consumer<String> cs){
        cs.accept(s);
    }

}

运行结果:

今天天气:多云
今天天气:晴天

Supplier:

public class TestSupplier {

	public static void main(String[] args) {
		Supplier<Integer> sp = () -> {
			int nums = 0;
			for (int i = 0; i < 50; i++) {
				nums += i;
			}
			return nums;
		};
		int sum = sp.get();
		System.out.println(sum);

		int n = m(50, () -> new Random().nextInt(500));
		System.out.println(n);

	}

	public static int m(Integer i, Supplier<Integer> sp) {
		int nums = 0;
		for (int j = 1; j <= i; j++) {
			nums += sp.get();
		}
		return nums;
	}

}

运行结果:

1225
12110
随机

Function:

public class TestFunction {

	public static void main(String[] args) {
		List<String> li = new ArrayList<String>();
		li.add("阿杰");
		li.add("光芒");
		li.add("公民");
		li.add("阿辉");
		int nums = m(li, (e)-> {if(e.startsWith("阿")){return 1;}
		else{return 0;}
		} );	
		System.out.println(nums);
		
		
		
		
	}
	public static int m(List<String> li, Function<String,Integer> ft){
		int nums = 0;
		for (String string : li) {
			nums += ft.apply(string);
		}
		return nums;
	}

}

运行结果:

2

Predicate:

public class TestEmployee {

	public static void main(String[] args) {
		Employee emp = new Employee("阿杰", 21,"男");
		Employee emp1 = new Employee("公民", 23,"男");
		Employee emp2 = new Employee("光芒", 22,"男");
		
		List<Employee> li = new ArrayList<Employee>();
		li.add(emp);
		li.add(emp1);
		li.add(emp2);
		
		List<Employee> newLi = m(li, (e)->e.getName().startsWith("阿"));
		for (Employee emps : newLi) {
			System.out.println(emps);
		}
	}
	public static List<Employee> m(List<Employee> li ,Predicate<Employee> pd){
		List<Employee> newli = new ArrayList<Employee>();
		for (Employee emp : li) {
			if(pd.test(emp)){
				newli.add(emp);
			}
		}
		return newli;
	
	}

}

运行结果:

Employee [name=阿杰, age=21, sex=男]
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值