Java8中 lambda表達式

1.用lambda表達式實現(xiàn)map

List cost = Arrays.asList(10.0,20.0,30.0);

cost.stream().forEach(x-> System.out.println(x));

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

cost.stream().map(x -> x + x*0.05).forEach(x -> System.out.println(x));



2.?用lambda表達式對集合進行迭代

List languages = Arrays.asList("java","scala","python");

//before java8

for(String each:languages) {

System.out.println(each);

}

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

//after java8

languages.forEach(x -> System.out.println(x));

languages.forEach(System.out::println);


3.用lambda表達式實現(xiàn)map與reduce

//map+reduce+lambda表達式

List 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);//63.0

等同于:

List 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);//63.0


4.filter操作

List cost = Arrays.asList(10.0,20.0,30.0,40.0);

List filteredCost = cost.stream().filter(x -> x >25.0).collect(Collectors.toList());

filteredCost.forEach(x -> System.out.println(x));//30.0? 40.0


5.與函數(shù)式接口Predicate配合

public static void filterTest(List languages, Predicate condition) {

? ?languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));? ?

?}

public static void main(String[] args) {

List 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);? ?

?}

返回結(jié)果:

Language starts with J:

Java

Language ends with a:

Java

scala

All languages:

Java

Python

scala

Shell

R

No languages:

Language length bigger three:

Python

scala

Shell



6.替代匿名內(nèi)部類

new Thread(new Runnable() {

? ? ? ? ? ? @Override? ? ? ? ? ? public void run() {

? ? ? ? ? ? ? ? System.out.println("The old runable now is using!");

? ? ? ? ? ? }

? ? ? ? }).start();

等同于

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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容