Stream的中间操作
.
筛选与切片
1- 筛选与切片
@Test
public void test1(){
List
<Employee> list
= EmployeeData
.getEmployees();
Stream
<Employee> stream
= list
.stream();
stream
.filter(e
-> e
.getSalary() > 7000).forEach(System
.out
::println
);
System
.out
.println("==========================================================================");
list
.stream().limit(5).forEach(System
.out
::println
);
System
.out
.println("==========================================================================");
list
.stream().skip(3).forEach(System
.out
::println
);
System
.out
.println("==========================================================================");
list
.add(new Employee(1010,"刘强东",40,8000));
list
.add(new Employee(1010,"刘强东",40,8000));
list
.add(new Employee(1010,"刘强东",42,8000));
list
.add(new Employee(1010,"刘强东",40,8000));
list
.stream().distinct().forEach(System
.out
::println
);
}
.
映射
2- 映射
@Test
public void test2(){
List
<String> list
= Arrays
.asList("aa", "bb", "cc", "dd");
list
.stream().map(str
-> str
.toUpperCase()).forEach(System
.out
::println
);
List
<Employee> employees
= EmployeeData
.getEmployees();
employees
.stream().map(e
->e
.getName()).filter( employee
-> employee
.length()>3).forEach(System
.out
::println
);
list
.stream().flatMap(StreamAPITest1
::fromStringToStream
).forEach(System
.out
::println
);
}
public static Stream
<Character> fromStringToStream(String str
){
ArrayList
<Character> list
= new ArrayList<>();
for (Character c
: str
.toCharArray()){
list
.add(c
);
}
return list
.stream();
}
.
排序
@Test
public void test3(){
List
<Integer> list
= Arrays
.asList(12, -54, 32, 8, 146, 21, 1);
list
.stream().sorted().forEach(System
.out
::println
);
List
<Employee> employeeList
= EmployeeData
.getEmployees();
employeeList
.stream().sorted((e1
,e2
) -> {
int compare
= Integer
.compare(e1
.getAge(), e2
.getAge());
if (compare
!= 0){
return compare
;
}else {
int compare1
= Double
.compare(e1
.getSalary(), e2
.getSalary());
return compare1
;
}
}).forEach(System
.out
::println
);
}
转载请注明原文地址: https://lol.8miu.com/read-24699.html