I have a List<User> users
, where classUser
has one property username
. I also have anotherList<User> activeUsers
. Let users = activeUsers + inactiveUsers
. Now I want to extract inactiveUsers
from users
based on username
property. I solved this problem using two for-loops. I think this is not efficient way. so if anyone know how it can be done efficiently please let me know.
e.g. I have activeUsers[1,3] and users[1,2,3,4] and want to build inactiveUsers[2,4].
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.
In Java, you can use the Collection
interface's removeAll
method.
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("user1");
add("user2");
}};
Collection secondList = new ArrayList() {{
add("user1");
add("user1");
add("user3");
add("user4");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
The above code will produce the following output:
First List: [user1, user2]
Second List: [user1, user2, user3, user4]
Result: [user3, user4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With