List<SoReturnPicVO> collect = picList.stream().filter(x -> x.getType() == 1).collect(Collectors.toList());
List<String> collect2 = collect.stream().map(x -> x.getPicUrl()).collect(Collectors.toList());
我要将实体里的一个字段取出来List-String,但是要根据另一个字段进行判断,我写成了两句,请问怎么能把这两句合并一下,写成一句
picList.stream().filter(x -> x.getType() == 1).map(x -> x.getPicUrl()).collect(Collectors.toList());
public class UserModel {
private String name;
public UserModel(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "UserModel{" +
"name='" + name + '\'' +
'}';
}
}
UserModel userModel1 = new UserModel("1");
UserModel userModel2 = new UserModel("2");
UserModel userModel3 = new UserModel("3");
List<UserModel> userModelList = new ArrayList<>();
userModelList.add(userModel1);
userModelList.add(userModel2);
userModelList.add(userModel3);
List<String> names = userModelList.stream().filter((item) -> {
String name = item.getName();
return Integer.valueOf(name) > 1;
}).map(UserModel::getName).collect(Collectors.toList());
System.out.println(names);
这个是先filter在map的
List<String> collect2 = collect.stream().filter(x -> x.getType() == 1).map(x -> x.getPicUrl()).collect(Collectors.toList());
先map在filter
List<SoReturnPicVO> collect2 = collect.stream().map(x -> {
SoReturnPicVO so = new SoReturnPicVO();
so.setPicUrl( x.getPicUrl());
so.setType( x.getType());
return so;
})
.filter(x -> x.getType() == 1).collect(Collectors.toList());
这个时候集合里面是SoReturnPicVO,SoReturnPicVO对象里面只设置图片和类型两个字段的值。