Java8新特性JDK8之流操作map和filter函数

Java新特性玩转JDK8之流操作map和filter函数

map函数

  • 功能详情
    • 将流中的每一个元素 T 映射为 R(类似类型转换)

  • 使用场景
    • 转换对象,如javaweb开发中集合里面的DO对象转换为DTO对象

  • 示例
    • 当前端需要展示所有用户时,要避免返回过多信息,并防止暴漏数据库其他字段。
      • 定义User类,该类属性和数据库字段一 一对应。(id,用户名,密码)
public class User {

    private int id;

    private String name;

    private String pwd;

    public User(){

    }

    public  User(int id, String name,String pwd){
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
  - 定义UserDTO类,该类中属性为 前端需要展示的字段。(id,用户名)
public class UserDTO {

    private int userId;

    private String username;


    public UserDTO(){}

    public UserDTO(int userId, String username){
        this.userId = userId;
        this.username = username;
    }


    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public String toString() {
        return "UserDTO{" +
                "userId=" + userId +
                ", username='" + username + '\'' +
                '}';
    }
}
  - 主程序(将多余的 密码 属性清理掉)
public class Main {
    public static void main(String[] args) {
        List<User> list = Arrays.asList(new User(1,"小东","123"),new User(21,"jack","rawer"),
                new User(155,"tom","sadfsdfsdfsd"),
                new User(231,"marry","234324"),new User(100,"小D","122223"));
        List<UserDTO> userDTOList = list.stream().map(obj->{
            UserDTO userDTO = new UserDTO(obj.getId(),obj.getName());
            return userDTO;
        }).collect(Collectors.toList());
        System.out.println(userDTOList);
    }
}

filter函数

  • 功能详情
    • 过滤出流中符合条件的元素

  • 示例
    • 过滤出LIst中元素长度大于5的 元素
      • 主程序
public class Main {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("springboot", "springcloud", "redis", "git", "netty", "java", "html", "docker");

        List<String> resultList = list.stream().filter(obj -> obj.length() > 5).collect(Collectors.toList());

        System.out.println(resultList);
        // 打印 [springboot, springcloud, docker]
    }
}

原文:

点此跳转原文地址

你可能感兴趣的:(JDK8新特性学习笔记)