Given a simple Set<T>
, what is a good way (fast, few lines of code) to get any value from the Set
?
With a List
, it's easy:
List<T> things = ...; return things.get(0);
But, with a Set
, there is no .get(...)
method because Set
s are not ordered.
Get and Set You learned from the previous chapter that private variables can only be accessed within the same class (an outside class has no access to it). However, it is possible to access them if we provide public get and set methods. The get method returns the variable value, and the set method sets the value.
The Set. of is a static factory method that creates immutable Set introduced in Java 9. The instance created by Set.
Set contains() method in Java with Examples Set. contains() method is used to check whether a specific element is present in the Set or not. So basically it is used to check if a Set contains any particular element.
A Set<T>
is an Iterable<T>
, so iterating to the first element works:
Set<T> things = ...; return things.iterator().next();
Guava has a method to do this, though the above snippet is likely better.
Since streams are present, you can do it that way, too, but you have to use the class java.util.Optional
. Optional
is a wrapper-class for an element or explicitely no-element (avoiding the Nullpointer).
//returns an Optional. Optional <T> optT = set.stream().findAny(); //Optional.isPresent() yields false, if set was empty, avoiding NullpointerException if(optT.isPresent()){ //Optional.get() returns the actual element return optT.get(); }
Edit: As I use Optional
quite often myself: There is a way for accessing the element or getting a default, in case it's not present:optT.orElse(other)
returns either the element or, if not present, other
. other
may be null
, btw.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With