I\'ve seen other questions about getting objects from Set
\'s based on index value and I understand why that is not possible. But I haven\'t been able to find a
Java Map/Collection Cheat Sheet
Will it contain key/value pair or values only?
1) If it contains pairs, the choice is a map. Is order important?
. 1-1) If yes, follow insertion order or sort by keys?
. . 1-1-1) If ordered, LinkedHashMap
. . 1-1-2) If sorted, TreeMap
. 1-2) If order is not important, HashMap
2) If it stores only values, the choice is a collection. Will it contain duplicates?
. 2-1) If yes, ArrayList
. 2-2) If it will not contain duplicates, is primary task searching for elements (contains/remove)?
. . 2-2-1) If no, ArrayList
. . 2-2-2) If yes, is order important?
. . . 2-2-2-1) If order is not important, HashSet
. . . 2-2-2-2) If yes, follow insertion order or sort by values?
. . . . 2-2-2-2-1) if ordered, LinkedHashSet
. . . . 2-2-2-2-2) if sorted, TreeSet
If you want to know that new Foo("1");
object is already present in the set
then you need to use contains
method as:
boolean present = set.contains(new Foo("1"));
The get
kind of method i.e. set.get(new Foo("1"));
is not supported because it doesn't make sense. You are already having the object i.e. new Foo("1")
then what extra information you would be looking through get
method.
As everyone mentioned before, there is no such method and for good reasons. That being said, if you wish to get a certain object from a HashSet in java 8 using a one-liner (almost), simply use streams. In your case, it would be something like:
Foo existing = set.stream().filter(o -> o.equals(new Foo("1"))).collect(Collectors.toList()).iterator().next();
Note that an exception will be thrown if the element doesn't exist so it is technically not a one-liner, though if the filter is properly implemented it should be faster than a traditional iteration over the collection elements.
HashSet is a little bit simplier than HashMap. If you don't need the features of HashMap, why use it? If the method like getObject(ObjectType o) was implemented by Java we dont need to iterate over the set after calling contain() methode...
get(Object o) is useful when we have one information linked to other information just like key value pair found in HashMap .So using get() method on one information we can get the second information or vice-versa.
Now, if HashSet provides get(Object o) method you need to pass an object. So if you have the object to pass to the get(Object o) method that means you already have the object, then what is need of get(Object o) method.