Java-Stream filter 过滤数据

filter可用于条件过滤list集合中的元素。

一、filter 条件过滤

public void test()
{
    List<userInfo> userList = new ArrayList<>();
    //userInfo字段 UserId; Age; NickName; Sex 1:男  2:女
    userList.add(new userInfo(1,22,"小明",1));
    userList.add(new userInfo(2,22,"小红",2));
    userList.add(new userInfo(3,24,"小张",1));

    //过滤出年龄大于22的用户
    List<userInfo> filterUser1 = userList.stream().filter(s -> s.getAge() > 22).collect(Collectors.toList());

    //过滤出年龄等于22,且是男性用户
    List<userInfo> filterUser2 = userList.stream().filter(s -> s.getAge() > 22 && s.getSex() == 1).collect(Collectors.toList());

}

public void test1()
{
    List<String> strings = Arrays.asList("a", "", "b", "c");

    //过滤出"a" "b"
    List<String> filterUser1 = strings.stream().filter(s -> s.equals("a") || s.equals("b")).collect(Collectors.toList());
}

Java-Stream filter 过滤数据_第1张图片

你可能感兴趣的:(Java)