This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

compare two Sets  RSS feed

 
kri shan
Ranch Hand
Posts: 1489
  • 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: 55717
163
  • 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
Bartender
Posts: 2054
44
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
Saloon Keeper
Posts: 7808
142
  • 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: 55717
163
  • 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: 1601
35
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>
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!