英文:
How to check a treeset contains at least one items from another treeset
问题
我有一个TreeSet,其中包含用户选择的项目,我正在尝试与另一个包含所有项目的基本TreeSet进行检查。如果用户选择的集合中至少包含一个基本TreeSet中的项目,我应该返回true。
以下是我的代码:
Set<String> baseItems = new TreeSet<>(Arrays.asList("HEALTH", "SPORTS", "GAMES", "COURSE", "FITNESS"));
Set<String> userItems = getRequestedItems();
// userItems的值类似于 HEALTH,SPORTS
// 如果userItems包含基本列表baseItems中的任何项目,应返回true。
boolean isMatch = !Collections.disjoint(baseItems, userItems);
如何比较userItems与baseItems,以确保他们选择了特定的项目?
英文:
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?
答案1
得分: 2
你可以使用 Collections.disjoint() 方法:
boolean isMatch = (!userItems.isEmpty()) && (!Collections.disjoint(baseItems, userItems));
具体而言,如果 baseItems
中至少有一个成员也在 userItems
中,则集合不是不相交的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论