In java-8 you can use stream and collectors as below,
Logic is
1. find command attribute in two lists
2. convert a smaller list to Map<Common_attribute, Actual_List_Object>, O(n) complexity
3. iterate the bigger list and check in a map if it contains, and add it in another list, O(n) complexity (map lookup is ~ O(1)) with O(n) space complexity,
else it would be O(n^2) (Accepted answer's complexity)
Assumed user's class as
class User {
private String name;
private String getName() {
return this.name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
// code which serves the purpose
import java.util.stream.Collectors;
ArrayList<String> names = new ArrayList<>();
ArrayList<User> users = new ArrayList<>();
//adding to name list
names.add("a");
//adding to User list
User user = new User();
user.name = "a";
User user2 = new User();
user2.name = "b";
users.add(user);
users.add(user2);
// Using user's name as key, you can specify any data type as key and create a map
Map<String, User> nameUserMap = users.stream().collect(Collectors.toMap(user1 -> user1.getName(), user1 -> user1));
System.out.println(nameUserMap);
List<User> filteredList = names
.stream()
.map(nameUserMap::get)
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println(filteredList);
output:
{a=User{name='a'}, b=User{name='b'}}
[User{name='a'}]