Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract List of object from another List of objects

Tags:

java

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].

like image 633
Diganta Avatar asked Apr 14 '13 13:04

Diganta


People also ask

How do I get a List of fields from a List of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do you combine two lists of 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.


1 Answers

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]
like image 122
Fahim Parkar Avatar answered Oct 03 '22 01:10

Fahim Parkar