ラムダ式の実装コードの一部

コードインターフェース機能型の4種類:

消費者:

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);
    }

}

結果:

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

サプライヤー:

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
随机

関数:

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

述語:

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=男]
公開された46元の記事 ウォンの賞賛132 ・は 10000 +を見て

おすすめ

転載: blog.csdn.net/S9264L/article/details/105037405
おすすめ