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

get value from set java
get first element from set java
java set to list
java set iterable
how to return a set in java
when to use set in java
java iterate set
java hashset

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.

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.

Java – How to get the first item from Set –, Which one is better here? iterator or stream? Vote Up4Vote Down Reply. 9 months  how to set values in object using java and what are the ways? how to set values in object using java and what are the ways? Java Swing Set And Get Values.

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 =;

//Optional.isPresent() yields false, if set was empty, avoiding NullpointerException
    //Optional.get() returns the actual element
    return optT.get();

Java Set, This Java Set tutorial explains how the Java Set interface and its It is considered good practice to alway specify a generic type for a will have the value 3, because the Set created in the example had 3 elements added to it. How to get the value of System Property and Environment Variable in Java? How to get the value of Environment variables? The System class in Java provides a method named System.getenv() which can be used to get the value of an environment variable set in the current system.

Getting any element from a Set or Collection may seem like an uncommon demand - if not arbitrary or eclectic - but, it is quite common when one, for example, needs to calculate statistics on Keys or Values objects in a Map and must initialise min/max values. The any element from a Set/Collection (returned by Map.keySet() or Map.values()) will be used for this initialisation prior to updating min/max values over each element.

So, what options one has when faced with this problem and at the same time trying to keep memory and execution time small and code clear?

Often you get the usual: "convert Set to ArrayList and get the first element". Great! Another array of millions of items and extra processing cycles to retrieve objects from Set, allocate array and populate it:

HashMap<K,V> map;
List<K> list = new ArrayList<V>(map.keySet()); // min/max of keys
min = max = list.get(0).some_property(); // initialisation step
 if( min > list.get(i).some_property() ){ ... }

Or one may use looping with an Iterator, using a flag to denote that min/max need to be initialised and a conditional statement to check if that flag is set for all the iterations in the loop. This implies a lot of conditional checking.

boolean flag = true;
Iterator it = map.keySet().iterator();
while( it.hasNext() ){
  if( flag ){
    // initialisation step
    min = max =;
    flag = false;
  } else {
    if( min > list.get(i).some_property() ){ min = list.get(i).some_property() }

Or do the initialisation outside the loop:

HashMap<K,V> map;
Iterator it = map.keySet().iterator();
K akey;
if( it.hasNext() ){
  // initialisation step:
  akey =;
  min = max = akey.value();
  do {
    if( min > list.get(i).some_property() ){ min = akey.some_property() }
  } while( it.hasNext() && ((!=null) );

But is it really worth all this manouvre on the behalf of the programmer (and setting up the Iterator on behalf of the JVM) whenever min/max's needed?

The suggestion from a javally-correct ol' sport could well be: "wrap your Map in a class which keeps track of min and max values when put or deleted!".

There is another situation which in my experience the need for just any item from a Map arises. This is when the map contains objects which have a common property - all the same for all of them in that map - and you need to read that property. For example suppose there is a Map of holding bins of the same histogram which have the same number of dimensions. Given such a Map you may need to know the number of dimensions of just any Histobin in the Map in order to, say, create another Histobin of the same dimensions. Do I need to setup an iterator again and dispose it after calling next() just once? I will skip the javally-correct person's suggestion to this situation.

And if all the trouble in getting the any element causes insignificant memory and cpu cycles increase, then what about all the code one has to write just to get the hard-to-get any element.

We need the any element. Give it to us!

Should "Set" have a Get method?, That Get method is effectively, "get me this value , please", to which the . Ergo, it shouldn't change and therefore Dictionary<String, MyClass> is a good solution for We can represent each equivalence class through any member of that Specifically in Java, HashSet was initially implemented using a  The get methods (also called an accessor method) return the value of the member they are associated with and the set method (also called a mutator method) sets the member to a new value. Using get and set methods aids maintainability, flexibility and extensibility.

A Guide to HashSet in Java, A quick but comprehensive introduction to HashSet in Java. to review most commonly used methods and have a look at some simple examples. It'd be a good idea to get familiar with the hashcode first to get a detailed Whenever an object is passed to this method, the hash value gets calculated. The easiest way, using standard Java classes, is static final Set<Integer> NECESSARY_PERMISSIONS = Collections.unmodifiableSet(new HashSet<Integer>(Arrays.asList(1, 2, 3, 6))); But you can also use a static initializer, or delegate to a private static method:

The Unified Process Construction Phase: Best Practices in , For example, irect.hpp is a good name for the header file in which class Accessors are methods that either set an object's data value or that return the data's For example, the Java 1.1 and 1.2 frameworks have an as String method on the  Getting any element from a Set or Collection may seem like an uncommon demand - if not arbitrary or eclectic - but, it is quite common when one, for example, needs to calculate statistics on Keys or Values objects in a Map and must initialise min/max values.

Retrieving Elements from Collection in Java (For-each, Iterator , How to set Precision for Double values in Java? Difference between Following are the 4 ways to retrieve any elements from a collection object: For-each. The Java Set interface is a standard Java interface, and it is a subtype of the Java Collection interface, meaning Set inherits from Collection. You can add any Java object to a Java Set. If the Set is not typed, using Java Generics, then you can even mix objects of different types (classes) in the same Set.

  • Actually, when you don't want a default, we want you to go ahead and use iterator().next(). (This is why we don't have a getFirst(Iterable<E>), just a getFirst(Iterable<E>, E default).)
  • @GanGnaMStYleOverFlowErroR: Yes.…
  • ...What?! No, it isn't. For any Set implementation I know of, this is at most O(log n).
  • True, but extremely rare in practice. (Also, easily addressed by using a LinkedHashSet.)
  • (Also, I claim no faster solution exists.)
  • I wonder if this is faster or slower than set.iterator().next();.
  • set.iterator().next() will throw a NoSuchElementException in case the collection is empty, using findAny of Stream is safer since it'll give you an empty Optional if the the collection is empty. I would err on safety unless performance is really important. Really depends on what you need.