-3

I have a Map (called masterMap) and a Set.

masterMap contains these values - {1537=OK, 1538=OK, 1539=OK, 4003=OK}

Set selectedSet =new HashSet();
selectedSet.add(Integer.parseInt("4003"));
boolean compareMapAndSet=masterMap.keySet().equals(selectedSet);

But, even though 4003 exists in the map, compareMapAndSet is always false.

What is wrong in the comparison?

reza.cse08
  • 5,938
  • 48
  • 39
user2488578
  • 896
  • 4
  • 21
  • 40
  • 1
    Er, they're not equal. `selectedSet` doesn't contain 1537, 1538 or 1539. – Andy Turner May 26 '16 at 13:11
  • 1
    Why set of one element should be equal to set of 4 elements? – Argb32 May 26 '16 at 13:12
  • They will always be different objects. You need to compare the actual contents for equality, or use contains or something, if you only need existence of the specific value in question. – ManoDestra May 26 '16 at 16:57

2 Answers2

3

equals compares whether or not the objects are equal. It doesn't check whether the second set is a subset of the first. To get that functionality, you should use containsAll

boolean compareMapAndSet=masterMap.keySet().containsAll(selectedSet);
resueman
  • 10,572
  • 10
  • 31
  • 45
0

From Sets public boolean equals(Object o)

Compares the specified object with this set for equality. Returns trueif the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface.
This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).

Note: But in your given example your selectedSet doesn't have same element.

I think you want to check if all element in selectedSet set is part of masterMap.keySet()

For that there is no stranded API you have to iterate over you set selectedSet and check it in masterMap.keySet() if it exists. like below code:

boolean compareMapAndSet = checkSubSet(masterMap.keySet(), selectedSet);
private static boolean checkSubSet(Set<Integer> keySet, Set<Integer> selectedSet) {
    for (Integer integer : selectedSet) {
        if (!keySet.contains(integer)) {
            return false;
        }
    }
    return true;
}

See the output result

Zoe
  • 27,060
  • 21
  • 118
  • 148
Sumit Singh
  • 15,743
  • 6
  • 59
  • 89