List按照对象中某个属性的值切割为多个对象,其他字段值不变,转为新的List


import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collection;
import java.util.stream.Collectors;


public class StreamController {

    static class User {

        public User(String userName, String score, String userCode, String phone) {
            this.userName = userName;
            this.score = score;
            this.userCode = userCode;
            this.phone = phone;
        }

        private String userName;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getScore() {
            return score;
        }

        public void setScore(String score) {
            this.score = score;
        }

        public String getUserCode() {
            return userCode;
        }

        public void setUserCode(String userCode) {
            this.userCode = userCode;
        }

        public String getPhone() {
            return phone;
        }

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

        private String score;
        private String userCode;


        private String phone;


    }

    public static void main(String[] args) {
        List<User> userList = new ArrayList();
        userList.add(new User("李四", "10,20,30", "lisi", "100001"));
        userList.add(new User("王五", "40,90,80", "wangwu", "100002"));
        userList.add(new User("张三", "50,60,70", "zhangsan", "100003"));

        //处理联合拟稿单位是多个值的情况
        List<User> scorePoList = userList.stream().map(user -> {
            String unitNameIds = user.getScore();
            if (StringUtils.isNotBlank(unitNameIds) && unitNameIds.contains(",")) {
                return Arrays.stream(unitNameIds.split(",")).map(un -> {
                    User newUser = new User(user.getUserName(), un, user.getUserCode(), user.getPhone());
                    return newUser;
                }).collect(Collectors.toList());
            } else {
                return Arrays.asList(user);
            }
        }).flatMap(Collection::stream).collect(Collectors.toList());

        System.out.println(JSONObject.toJSONString(scorePoList));
    }
}

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