-1

I have this list of array :

List<String> keyList = ["key1", "key2", "key3"]

And I have a list of objects like this:

[{
"key1": 1,
"key2": 2,
"key3": 3,
"key4": 4
}, {
"key1": 2,
"key2": 4,
"key3": 6,
"key4": 7
}]

And I want to only take those elements that I have in keyList.

So in final list, I won't have "key4".

My approach was to use two for loops - first for the list of objects and then keyList.

I need to know if there's any better approach to do this. Maybe an inbuilt function that I am not aware of.

Note: One is List, other is List. I don't think I can just compare or take the intersection of these two List.

nirvair
  • 4,001
  • 10
  • 51
  • 85
  • Possible duplicate of [Java Compare Two Lists](https://stackoverflow.com/questions/2762093/java-compare-two-lists) – yassadi Apr 04 '18 at 11:42
  • If the keys in the list of objects are going to be same in all objects, then we can identify the odd one out in the first object and remove it consecutive objects. If the object of keys are assumed to be a map, then we can achieve in with only 1 for loop – pushpavanthar Apr 04 '18 at 11:46
  • @yassadi I don't think the problem is similar. The second list is not a List, it is a List. – nirvair Apr 04 '18 at 18:15

1 Answers1

1

Basically, you want to find the intersection of two Collections.

Try something like this:

List<String> s1;
List<String> s2;
s1.retainAll(s2); 
Andres
  • 10,561
  • 4
  • 45
  • 63
  • This would happen if two list have same type - String. Here one is List and other is List. I need to make a new Dto where the keys present in this new dto would match the List. – nirvair Apr 04 '18 at 18:17