Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

Stream over a list to feed other lists in java

I have List<EmployeeDetails> which contains total list of employees among the organization.

EmployeeDetails.java

private String name;
private String designation;
//other property

I want loop over above list and feed the element into model class which contains many types of lists

Emoloyee.java

List<Manager> manager;
List<Intern> intern;
List<TeamLead> teamLead;
List<Support> support;


Manager.java

private String name;
private String designation;
//other property

How can I feed Employee.java by only single loop over List<EmployeeDetails>?

I know I can use for loop against list and create each type of list based on designation and feed to model but I am looking for a better approach where I don't want to create many list.

Is there any better approach where I can feed to model on-the-fly in single loop.

question from:https://stackoverflow.com/questions/65877373/stream-over-a-list-to-feed-other-lists-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try it like this. You may need to modify this to fit your exact requirement.

List<Manager> managers = new ArrayList<>();
List<Intern> interns = new ArrayList<>();
List<TeamLead> teamLeads = new ArrayList<>();
List<Support> support    = new ArrayList<>();

forEach(EmployeeDetails ed : employDetailList) {
    switch(ed.getDesignation()) {
        // get the proper info from `ed` to create the position objects.
        case "Manager": managers.add(new Manager(....);
        break;
        case "Intern": interns.add(new Intern(....));
        break;
        case "TeamLead": teamLeads.add(new TeamLead(....));
        break;
        case "Support": support.add(new Support(....));
        break;
    }
}

However, this is rather cumbersome. You may want to rethink your design. For example, have the different position classes be a subclass of Employee.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...