简体   繁体   中英

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.

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.

Using Java8 you can convert EmployeeDetails list to designation wise map as:

Map<String, List<EmployeeDetails>> designationListMap = employees.stream().collect(Collectors.groupingBy(EmployeeDetails ::getDesignation));

and after you can retrieve a list of EmployeeDetails for specific designation:

designationListMap.get("Manager");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM