提出問題
java的lambda表達式和Stream如何使用? ? ?
解決問題
Lambda表達式的語法
基本語法:
[code](parameters) -> expression 或 (parameters) ->{ statements; }
看範例學習吧!
例一:定義一個AyPerson類,為之後的檢定做準備。
[code]package com.evada.de; import java.util.Arrays; import java.util.List; class AyPerson{ private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public AyPerson(String id, String name) { this.id = id; this.name = name; } } /** * Created by Ay on 2016/5/9. */ public class LambdaTest { public static void main(String[] args) { List<String> names = Arrays.asList("Ay", "Al", "Xy", "Xl"); names.forEach((name) -> System.out.println(name + ";")); } }
上面的範例names.forEach((name) -> System.out.println(name + “;”));
類似:
function(name){//name为参数 System.out.println(name + “;”);//方法体 }
[code]Ay; Al; Xy; Xl;
例二:
[code]List<Student> personList = new ArrayList<>(); personList.add(new Student("00001","Ay")); personList.add(new Student("00002","Al")); personList.add(new Student("00003","To")); personList.forEach((person) -> System.out.println(person.getId()+ ":" + person.getName()));
結果:
[code]00001:Ay 00002:Al 00003:To
例二:把下面程式碼上面main函數中
[code]List<AyPerson> personList = new ArrayList<>(); personList.add(new AyPerson("00001","Ay")); personList.add(new AyPerson("00002","Al")); personList.add(new AyPerson("00003", "To")); //stream类中的filter方法 personList.stream() //过滤集合中person的id为00001 .filter((person) -> person.getId().equals("00001")) //将过滤后的结果循环打印出来 .forEach((person) -> System.out.println(person.getId() + ":" + person.getName()));
結果:
[code]00001:Ay
例三:Lambda和Stream類別中f**ilter()**方法
[code] List<AyPerson> personList = new ArrayList<>(); List<AyPerson> newPersonList = null; personList.add(new AyPerson("00001","Ay")); personList.add(new AyPerson("00002","Al")); personList.add(new AyPerson("00003", "To")); //将过滤后的结果返回到一个新的List中 newPersonList = personList.stream() .filter((person) -> person.getId().equals("00002")).collect(Collectors.toList()); //打印结果集 newPersonList.forEach((person) -> System.out.println(person.getId() + ":" + person.getName()));
[code]00002:Al
除了可以放到List中,還可以放到Set中等等…結果:rrreee
Stream中還有很多好用的方法可以使用,例如count,limit等等可以自己到API學習
以上就是Java之Lambda表達式和Stream類簡單例子的內容,更多相關內容請關注PHP中文網(www.php.cn)!