0

Assuming I have a set. I would like to get back a certain element. I have an element that I created which has its key fields (used by compareTo) but not the other fields. The real element is in the set. The contains method returns true but I want the element itself. This should be done efficiently. How can that be done?

  • It can be done by using `Map` instead of `Set`, using the same object for both key and value. Since `Set` internally uses a `Map` anyway, it'll use the same amount of memory. – Andreas Jun 07 '20 at 08:45
  • Please add a code in your post – Vinay Hegde Jun 07 '20 at 08:48
  • You can encapsulate the key fields you mentioned into an object that can be used as the key in the `Map` – prhcummins Jun 07 '20 at 08:52
  • Set collection serves to check presence of elements, but not to retrieve them, use map instead! https://docs.oracle.com/javase/8/docs/api/java/util/Set.html https://docs.oracle.com/javase/8/docs/api/java/util/Map.html – Alex Jun 07 '20 at 08:57

0 Answers0