java8 stream操作,常用业务

实体类

public class User {
    private String name;
    private String phone;
    private String idCard;

    public User() {
    }

    public User(String name, String phone, String idCard) {
        this.name = name;
        this.phone = phone;
        this.idCard = idCard;
    }

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getIdCard() {
        return idCard;
    }

    public void setIdCard(String idCard) {
        this.idCard = idCard;
    }

    public static List getUsers(){
        List list = new ArrayList<>();
        list.add(new User("张三", "13800138000", "64011119890034"));
        list.add(new User("李四", "13800138001", "83011119890039"));
        list.add(new User("张三", "13800138002", "64111119890030"));
        list.add(new User("周姐西", "13800138003", "64111119890030"));
        list.add(new User("西门吹灯", "13800138004", "64111119890038"));

        return list;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                ", idCard='" + idCard + '\'' +
                '}';
    }

测试方法

public class StreamTest {
        @Test
        public void test1() {
            List users = User.getUsers();

            System.out.println("原始数据:");
            users.stream().forEach(System.out::println);

            System.out.println();
            System.out.println("同时给姓名、手机号加*,并返回新list:");
            List list3 = users.stream().map(u -> {
                String name = u.getName();
                name = "*" + name.substring(1);
                u.setName(name);
                return u;
            }).map(u -> {
                String phone = u.getPhone();
                String newPhone = phone.substring(0, 3) + "****" + phone.substring(7);
                u.setPhone(newPhone);
                return u;
            }).collect(Collectors.toList());
            list3.stream().forEach(System.out::println);

           
        }
}

结果

             原始数据:
             User{name='张三', phone='13800138000', idCard='64011119890034'}
             User{name='周姐西', phone='13800138003', idCard='64111119890030'}
             User{name='西门吹灯', phone='13800138004', idCard='64111119890038'}

             同时给姓名、手机号加*,并返回新list:
             User{name='*三', phone='138****8000', idCard='64011119890034'}
             User{name='*姐西', phone='138****8003', idCard='64111119890030'}
             User{name='*门吹灯', phone='138****8004', idCard='64111119890038'}

你可能感兴趣的:(java8 stream操作,常用业务)