• Post Reply Bookmark Topic Watch Topic
  • New Topic

compare two Sets

 
kri shan
Ranch Hand
Posts: 1481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to compare Set<Custom-Object> with Set<String>.


Set<Custom-Object> set1 = foo();

set1 has sunday and monday (2 values)


Set<String> set2 = new HashSet<>();
set2.add("sunday");
set2.add("monday");


set1.equals(set2) returns false.

 
Campbell Ritchie
Marshal
Posts: 52581
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How on earth will a set of custom objects be equal to a set of Strings? Unless they are both empty.
 
Paweł Baczyński
Saloon Keeper
Posts: 1955
38
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, maybe OP didn't mean equal by the means of equals() method.
Maybe OP meant equal defined as: for every entry in custom-object-set (name it entry) check if there is entry.toString() in the string-set. Maybe.
We can not know for sure until OP clarifies the requirements.
 
Stephan van Hulst
Bartender
Posts: 6583
84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming Paweł's assumption, I would probably map-collect the first set to a new set of Strings, and then compare that to the second set.
 
Campbell Ritchie
Marshal
Posts: 52581
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. If Paweł is correct about this new meaning for equality, that would work.
 
salvin francis
Bartender
Posts: 1407
18
Eclipse IDE Google Web Toolkit Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for the actual comparison, Set.containsAll() method might be helpful (given that you just want to see that all elements in one set is contained in another) or simply equals() method (I haven't tried it for a set)
However, as others have pointed out it does not make sense to compare two objects if they represent something else.

Its like saying i want to compare Set<Zombies> with Set<Zebras>
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!