I have 2 arrays of User Objects. 1 array contains list of all users and 2nd array contains list of all logged in Users. Which is the best way to find non-logged in users
            Asked
            
        
        
            Active
            
        
            Viewed 290 times
        
    1
            
            
        - 
                    That's called a set difference. Are the arrays sorted? Otherwise I'd recommend you to use a `HashSet`. – Luatic Jun 15 '22 at 10:30
- 
                    @LMD- Arrays are not sorted – ravi Jun 15 '22 at 10:32
- 
                    1[java.util.Collection#removeAll](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Collection.html#removeAll(java.util.Collection)) – Abra Jun 15 '22 at 10:37
- 
                    Is it possible to do it without collections? and without linear search in Array? – ravi Jun 15 '22 at 10:38
1 Answers
0
            
            
        There are two cases:
- If you do not have equals and hash code methods implemented in User:
then the simplest way would be to get all UserIdentifier, like databaseId or username. Persist it in a hashed structure, for fast search. Then go through all Users and accept all not contained in this collection.
Create a set of logged user Identifiers:
 Set<Long> loggedUserIdentifiers = loggedUsers.stream()
                                   .map(User::getId) // I have chosen Id
                                   .collect(toSet());
Now you can find all not-logged users:
 List<User> unloggedUsers = allUsers.stream()
                            .filter( user -> !loggedUserIdentifiers.contains(user.getId()))
                            .collect(toSet());
- If you have equals and hash code implemented, then you could simply remove all logged users from a copy of all Users collection. Just remember to create a copy first, otherwise You will end with only logged and not-logged Users. - Set<User> allUserCopy = new HashSet<>(allUsers); // works on lists also allUserCopy.removeAll(loggedUsers); Set<User> notLoggedUsers = Set.copyOf(allUserCopy);
Now you will have a collection with only not logged users.
 
    
    
        Beri
        
- 11,470
- 4
- 35
- 57
- 
                    Thanks for the answer. Is it possible to do it without collections? and without linear search in Array? – ravi Jun 15 '22 at 10:37
- 
                    @ravi There is no linear search involved here (rather a set lookup is used), only looping over all users to find all non-logged-in ones. – Luatic Jun 15 '22 at 10:38
