stream.filter一般适用于list集合,主要作用就是模拟sql查询,从集合中查询想要的数据。filter里面的参数user是指集合里面的每一项
public class StreamTest{
public static void main(String[] args){
List list = new ArrayList<>();
//定义三个用户对象
User user1 = new User();
user1.setUsername("huxiansen");
user1.setPassword("123456");
User user2 = new User();
user2.setUsername("huxianseng");
user2.setPassword("123456");
User user3 = new User();
user3.setUsername("huxiansen");
user3.setPassword("12345");
//添加用户到集合中
list.add(user1);
list.add(user2);
list.add(user3);
?
//在集合中查询用户名为huxiansen的集合
List userList = list.stream().filter(user -> "huxiansen".equals(user.getUsername())).collect(Collectors.toList());
//在集合中查询出第一个用户密码为123456的用户
Optional user = list.stream().filter(userTemp -> "123456".equals(userTemp.getPassword())).findFirst();
?
System.out.println(userList);
System.out.println(user);
}
}