filter,map,foreach区别
filter,筛选出符合条件的元素。
map,将list中的每一个元素映射为自定义元素。
foreach,对list中每一个元素进行操作。
区别:
- filter和map不影响原来的list,其结果返回一个新list。foreach对原来的list进行操作。
- filter返回对象和原list相等,返回的list长度小于或等于原list。map返回对象为任意值,且map返回的list长度和原list相等(一对一映射)。
filter 过滤元素
//方式一
List<Student> resList = students.stream.filter(o -> o.getId() != null && "张三".euqals(o.getName).collect(Collectors.toList());
//方式2
List<Student> resList = students.stream.filter(o -> {
if(o.getId() != null && "张三".equals(o.getName)){
return true;}
else{
return false;}
});
map重新组装元素
//方式一 顺便去null,去重
List<String> names = students.stream.map(Student :: getName).distinct().filter(o -> o.getName != null).collect(Collectors.toList());
//方式二
List<String> names = students.stream.map(o > {
String name = o.getName;
return name;
})..collect(Collectors.toList());