Why doesn't java.util.HashSet have a get(Object o) method?

后端 未结 11 2270
暖寄归人
暖寄归人 2020-12-07 18:39

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

11条回答
  •  生来不讨喜
    2020-12-07 19:12

    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.

提交回复
热议问题