Java 检查一个树集值是否包含到另一个树集中

Java 检查一个树集值是否包含到另一个树集中,java,collections,Java,Collections,实际上,如果set1包含set2的一些值(b和d),我想返回true。如果集合中存在任何一个值,则应返回true class TreeSetExample{ public static void main(String[] args){ TreeSet set1 = new TreeSet(); TreeSet set2 = new TreeSet(); set1.add("a");

实际上,如果set1包含set2的一些值(b和d),我想返回true。如果集合中存在任何一个值,则应返回true

class TreeSetExample{

       public static void main(String[] args){
            TreeSet set1 = new TreeSet();
            TreeSet set2 = new TreeSet();

            set1.add("a");
            set1.add("b");
            set1.add("d");
            set1.add("e");

            set2.add("c");
            set2.add("b");
            set2.add("d");
            set2.add("g");

           boolean b1 = set1.contains(set2);// here i am getting classCastException
       }
    }

我知道contains只接受对象,不接受集合。那么,有没有办法检查两个树集之间的值呢(从
集合
接口派生),但仅当参数中集合的所有元素都包含在当前
集合
对象中时,才会返回true

要检查是否包含任何元素,可以使用流方法。
当然,您还应该使用泛型类型和非原始类型,因为您实际用于
TreeSet
,强烈建议不要使用这些类型

TreeSet<String> set1 = new TreeSet<>();
TreeSet<String> set2 = new TreeSet<>();

... 
boolean isAnyMatch = set2.stream()
                         .anyMatch(s2 -> set1.contains(s2));

System.out.println(isAnyMatch);
TreeSet set1=新树集();
TreeSet set2=新的TreeSet();
... 
布尔值isAnyMatch=set2.stream()
.anyMatch(s2->set1.contains(s2));
System.out.println(isAnyMatch);

您有
集合。containsAll(集合c)
(从
集合
接口派生),但仅当参数中集合的所有元素都包含在当前
集合
对象中时,才会返回true

要检查是否包含任何元素,可以使用流方法。
当然,您还应该使用泛型类型和非原始类型,因为您实际用于
TreeSet
,强烈建议不要使用这些类型

TreeSet<String> set1 = new TreeSet<>();
TreeSet<String> set2 = new TreeSet<>();

... 
boolean isAnyMatch = set2.stream()
                         .anyMatch(s2 -> set1.contains(s2));

System.out.println(isAnyMatch);
TreeSet set1=新树集();
TreeSet set2=新的TreeSet();
... 
布尔值isAnyMatch=set2.stream()
.anyMatch(s2->set1.contains(s2));
System.out.println(isAnyMatch);

首先,我建议您不要使用原始类型,而是使用泛型:

 TreeSet<String> set1 = new TreeSet<>();
 TreeSet<String> set2 = new TreeSet<>();

首先,我建议您不要使用原始类型,而是使用泛型:

 TreeSet<String> set1 = new TreeSet<>();
 TreeSet<String> set2 = new TreeSet<>();

查看Collections类中的方法。您是否查看了?包括继承的方法吗?您有
Set.containsAll(集合c)
(从
集合
接口派生),但仅当参数中集合的所有元素都包含在当前
集合
对象中时,才会返回true。耶。但是我想寻找特定的值,而不是所有的值@davidxxx@AkshayUttur因此,请根据此要求编辑您的问题检查Collections类中的方法。您查看了吗?包括继承的方法吗?您有
Set.containsAll(集合c)
(从
集合
接口派生),但仅当参数中集合的所有元素都包含在当前
集合
对象中时,才会返回true。耶。但是我想寻找特定的值,而不是所有的值@davidxxx@AkshayUttur所以用这个要求编辑你的问题谢谢你,它成功了。甚至感谢你接近我来遵循标准coding@AkshayUttur没问题,很高兴它帮了你;)使用
TreeSet
s,您只需小心确保它们具有相同/兼容的比较器。谢谢您,它成功了。甚至感谢你接近我来遵循标准coding@AkshayUttur没问题,很高兴它帮了你;)使用
TreeSet
s,您只需小心确保它们具有相同/兼容的比较器。