public class test {
//收集
@Test
public void test1(){
//collect(Collector c),Collector是收集人的意思,將流轉化爲其他形式
//Collector接口中方法的實現決定了如何對流執行收集的操作(如收集到List,Set,Map)
//Collectors實用類提供了很多靜態方法,可以方便地創建常見收集器實例,返回Collector
//Collectors中靜態方法toList List<T>把流中元素收集到List
//例子:查找工資大於6000的員工,結果返回爲一個List或者Set
//如果是放到List的當中
List<Employee> employees = EmployeeData.getEmployees();
List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());
//這裏用的是集合中的forEach方法
employeeList.forEach(System.out::println);//按照添加的順序輸出
System.out.println();
//如果是放到Set當中
Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());
employeeSet.forEach(System.out::println);//Collection實現了Iterable,而forEach方法是定義在Iterable當中的
//Set本身無序,所以輸出的順序會變
}
}
輸出結果爲:
Employee{id=1001, name='馬化騰', age=34, salary=6000.38}
Employee{id=1002, name='馬雲', age=12, salary=9876.12}
Employee{id=1004, name='雷軍', age=26, salary=7657.37}
Employee{id=1006, name='比爾蓋茨', age=42, salary=9500.43}
Employee{id=1001, name='馬化騰', age=34, salary=6000.38}
Employee{id=1002, name='馬雲', age=12, salary=9876.12}
Employee{id=1006, name='比爾蓋茨', age=42, salary=9500.43}
Employee{id=1004, name='雷軍', age=26, salary=7657.37}