Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get first item from a java.util.Set?

Tags:

java

set

I have a Set instance:

Set<String> siteIdSet = (Set<String>) pContext.getParent().getPropertyValue(getCatalogProperties().getSitesPropertyName()); 

The pContext.getParent().getPropertyValue() is out-of-the-box code upon which I don't have any control to modify.

Requirement:

I wanted to get the first default element out of it (always). However, I couldn't find a method get(index) like in an ArrayList.

Hence, right now, I am doing like this.

for (Iterator<String> it = siteIdSet.iterator(); it.hasNext();) {     siteId = it.next();     break; } 

Is there any (other) efficient way (short and better) of achieving this?

like image 965
KrishPrabakar Avatar asked Dec 11 '13 05:12

KrishPrabakar


People also ask

How do I access the first element in a Set?

begin() function is used to return an iterator pointing to the first element of the set container. begin() function returns a bidirectional iterator to the first element of the container. Syntax: setname.

How do I get the first element of a list?

The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index. Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.

How do I find the first value in a HashSet?

To create a Sorted Set, firstly create a Set. Set<Integer> s = new HashSet<Integer>(); Add elements to the above set.

Which method is used to get the first element from a?

The firstElement() method returns the first element of the Stack object.


1 Answers

This will return the first element

set.iterator().next(); 
like image 172
Sagar Koshti Avatar answered Sep 30 '22 17:09

Sagar Koshti