如何检查一个TreeSet是否包含另一个TreeSet中至少一项。

huangapple go评论81阅读模式
英文:

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&lt;String&gt; baseItems = new TreeSet&lt;String&gt;Arrays.asList(&quot;HEALTH&quot;,&quot;SPORTS&quot;,&quot;GAMES&quot;,&quot;COURSE&quot;,&quot;FITNESS&quot;));

Set&lt;String&gt; 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()) &amp;&amp; (! Collections.disjoint(baseItems, userItems));

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

huangapple
  • 本文由 发表于 2020年9月16日 05:09:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63909877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定