Home > database >  How to check whether a list is a subset of another list, regardless of order
How to check whether a list is a subset of another list, regardless of order

Time:08-11

How can I tell if String list is subset of another string Parent List?

 List<String> parentDataList:  {"abc", "def", "ghi", "xyz"} 
 List<String> child1:   {"def", "abc"} // this is a subset, regardless of order
 List<String> child2:   {"1234", "ghi"}   // not a subset, because 1234 not exist
 List<String> child3:   {"ghi", "xyz, "abc"}  // this is a subset, regardless of order

This answer accounts for sequence order, which I do not care about.

Get index of contain sublist from list java

return Collections.indexOfSubList(parentDataList, child1) != -1;

CodePudding user response:

You can check if the parent list contains all of those defined in child list. Let's say you've parentDataList as

List<String> parentDataList = new ArrayList<>();

and all of these "abc", "def", "ghi", "xyz" added. And do similar for all the child list you desire.

You can write whether parent data list has all of the data contained by child list as follows :

int parentSize = parentDataList.size();
int childSize = childDataList.size(); // after creating and adding element to child data list
boolean isSubset = parentDataList.containsAll(childDataList) && parentSize >= 
childSize;
System.out.println(isSubset);

Question arises what to do when list contains duplicate ? It's better to use Set /HashSet because it avoids duplicates and it's easier to maintain. But if you're sure to add only unique elements in ArrayList too, I believe this should work.

NOTE : Mathematically set has unique elements but you're declaring them as List which can has duplicates, so I have written with && operators and compared their size too.

  • Related