简体   繁体   中英

How to check a treeset contains at least one items from another treeset

I have a treeset contains user selected items and I am trying to check with another base treeset which contains all items. If the user-selected set contains at leaset one item from base treeset, I should return true.

Here is my code:

Set<String> baseItems = new TreeSet<String>Arrays.asList("HEALTH","SPORTS","GAMES","COURSE","FITNESS"));

Set<String> userItems = getRequestedItems();
// userItems has values like HEALTH,SPORTS

// if userItems contains or match with any items in the baseItems list it should return true.
boolean isMatch = requestedApiPillars.contains(apiPillars); // this returning class cast exception.

How do I compare userSet with baseItems to make sure they selected the specific items?

You can use Collections.disjoint() :

boolean isMatch = (! userItems.isEmpty()) && (! Collections.disjoint(baseItems, userItems));

Specifically, if at least one member of baseItems is also in userItems , the collections are not disjoint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM