How to split List into list of lists at run time based on property values

Viewed 63

How to split below list into list of lists based on name , salary and joining date without checking values. I want to do at runtime because I don't know values:

public class Employee {
    
    private String name;
    private long id;
    BigDecimal sal;
    private Date joinDate;
    public Employee(String name, long id, BigDecimal sal,Date date) {
        super();
        this.name = name;
        this.id = id;
        this.sal = sal;
        this.joinDate=date;
    }
    

}

List<Employee> employeeList =new ArrayList<>();
SimpleDateFormat format =new SimpleDateFormat("MMddYYYY");
employeeList.add(new Employee("Mike",1000,BigDecimal.valueOf(200),format.parse("08122022")));
employeeList.add(new Employee("David",1001,BigDecimal.valueOf(100),format.parse("08112022")));
employeeList.add(new Employee("Mike",1002,BigDecimal.valueOf(200),format.parse("08122022")));
employeeList.add(new Employee("David",1003,BigDecimal.valueOf(100),format.parse("08112022")));
employeeList.add(new Employee("David",1003,BigDecimal.valueOf(200),format.parse("08112022")));
employeeList.add(new Employee("David",1003,BigDecimal.valueOf(200),format.parse("08122022")));

Output should be list of list employee objects , above list should return 3 list of employee objects

If I run below it will give me list contain Mike objects but at runtime I don’t know what data list contains so I can’t do really this , so basically @ runtime above list should compare elements And final list should be list of list employee objects

List result = employeeList.stream().filter(emp-> emp.getName().equals("Mike")) .collect(Collectors.toList())

1 Answers

Based on your example, you could attempt something like the following:

List<List<Employee>> groupByName = new ArrayList<>();
employeeList.forEach(e -> {
    // Automatically start a new list and add first employee if no lists is present
    if(groupByName.isEmpty()) {
        List<Employee> newList = new ArrayList<>();
        newList.add(e);
        groupByName.add(newList);
    }
    else {
        // use a boolean to track whether the employee has been matched to a list
        boolean match = false;
        groupByName.forEach(l -> {
            // compare each employee to the first employee in each list
            if(l.get(0).getName().equals(e.getName()) {
                // if the names match, add to the current list, and break out of loop
                l.add(e);
                match = true;
                break;
            }
        });
        // if no match has been found for the current name, create a new list and add the employee
        if(!match) {
            List<Employee> newList = new ArrayList<>();
            newList.add(e);
            groupByName.add(newList);
        }
});

Using a similar process, you could filter the lists based on the other criteria as well.

Related