1

I have the following issue whereby I am comparing two Hash sets (both with String values in them). I need to compare both hash sets to keep only that data in set A which is also present in set B:

Set A has these values:

[YNVOTXAguONvMRiK8C6WzGAUlyf2] 
[YADfoWtZXSUtrMhN2JfhnS5lJYE3]

Set B has this value:

[YADfoWtZXSUtrMhN2JfhnS5lJYE3]

As you can notice, the 2nd key of set A and the key in set B are identical. However when I compare both sets using the code below, the result I get is false:

Log.e("boolean value", "" + chatList.get(i).userId.keySet().contains(userId.keySet()));

Can someone please point me in the right direction?

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79

3 Answers3

3

To compute elements common (intersection) to two sets, you can use method:

Set#retainAll(Collection c) 

In your example you check if set contains keySet, you should check for one value, so it could be:

Log.e("boolean value", "" + chatList.get(i).userId.keySet().contains(userId.keySet().iterator().next()));
Krzysztof Cichocki
  • 6,294
  • 1
  • 16
  • 32
1
contains(userId.keySet())

here are you checking if the set one has the collection object returned by userId.keySet()...

of course this will return false.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

As Krzysztof mentioned, you can use Set#retainAll(Collection c) to get the intersection of the two sets. This will however modify the existing set. If you don't want to modify the existing set, you can use one of the two following approaches:

With Java 8:

Set<String> intersection = a.stream()
                            .filter(b::contains)
                            .collect(Collectors.toSet());

Without Java 8:

Set<String> intersection = new HashSet<>(a);
intersection.retainAll(b);
Cyril S
  • 51
  • 6