-
public class StreamTest{ public static void main(String[] args){ List<User> 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<User> userList = list.stream().filter(user -> "huxiansen".equals(user.getUsername())).collect(Collectors.toList()); //在集合中查询出第一个用户密码为123456的用户 Optional<User> user = list.stream().filter(userTemp -> "123456".equals(userTemp.getPassword())).findFirst(); System.out.println(userList); System.out.println(user); } }
-