Search code examples
javaarraylistempty-list

Method returning Arraylist empty


I currently need a copy of a list returned in a method so I use it in a for-each. Class Employee extends User. I want a List returned only with the employees, which is an instance of User, but I think it's not working.

public ArrayList<Employee> getEmployeeList() {
        ArrayList<Employee> copy = new ArrayList<>();
        for(User user : ec.getUsersList().getUserList()){
            if(user instanceof Employee){
                copy.add((Employee) user);
            }
        }
        return copy;
    }

I want to use it here, and the for seems not to be running the list..

for (Employee a : c.getEmployeeList()) {
            if (!dispEmployee.contains(a)) {
                notSelectedEmployee.addElement(a.toString());
            }
        }

Solution

  • I'm a big fan of Java 8, lambdas, and a more functional style. I might write it like this:

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class Filter {
    
        public static List<Employee> getEmployeeList(List<User> users) {
            List<Employee> employees = new ArrayList<>();
            if (users != null) {
                employees = users.stream()
                        .filter(u -> u instanceof Employee)
                        .map(u -> (Employee) u)
                        .collect(Collectors.toList());
            }
            return employees;
        }
    }
    

    My JUnit test passed; I think it's good. User and Employee are simple guesses at what you were after.

    import org.junit.Assert;
    import org.junit.Test;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class FilterTest {
    
        @Test
        public void testFilter() {
            // setup
            List<User> users = new ArrayList<>();
            users.add(new User("foo", "bar"));
            users.add(new Employee("baz", "bat", "supervisor"));
            users.add(new User("x", "y"));
            users.add(new Employee("alpha", "omega", "developer"));
            List<Employee> expected = new ArrayList<>();
            expected.add((Employee) users.get(1));
            expected.add((Employee) users.get(3));
            // exercise
            List<Employee> actual = Filter.getEmployeeList(users);
            // assert
            Assert.assertEquals(expected, actual);
        }
    }