Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good way to get *any* value from a Java Set?

Tags:

java

set

any

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 Sets are not ordered.

like image 268
Jacob Marble Avatar asked Dec 03 '12 22:12

Jacob Marble


People also ask

Can we use get method in set in Java?

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.

What does set of () in Java?

The Set. of is a static factory method that creates immutable Set introduced in Java 9. The instance created by Set.

How do you check if a value is in a set Java?

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.


2 Answers

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.

like image 60
Jacob Marble Avatar answered Nov 12 '22 06:11

Jacob Marble


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.

like image 24
Dániel Somogyi Avatar answered Nov 12 '22 07:11

Dániel Somogyi