list stream:过滤对象集合中对象字段满足条件的对象集合

@Data
@Builder
class User{
    private String name;

    private int id;
}
public static void main(String[] args) {
    List<User> userList = new ArrayList<>();

    User user1 = User.builder().id(1).name("ONE").build();
    User user2 = User.builder().id(2).name("ZERO").build();
    User user3 = User.builder().id(3).name("TWO").build();
    User user4 = User.builder().id(4).name("FOUR").build();
    User user5 = User.builder().id(5).name("ONE").build();

    userList.add(user1);
    userList.add(user2);
    userList.add(user3);
    userList.add(user4);
    userList.add(user5);
    System.out.println("筛选前:" + userList);
    userList = userList.stream().filter(o -> o.getName().equals("ONE")).collect(Collectors.toList());
    System.out.println("筛选后:" + userList);
}

你可能感兴趣的:(jdk,java)