Search code examples
javacollectionshashsetlinkedhashset

How to fetch the first element in a collection in java


My question is, How to fetch the first element in a collection in java

Example :

LinkedHashSet h1 = new LinkedHashSet();   
h1.add("Ani","Broadway NY",10001);

And I want to fetch "Ani" only

How can I do this?


Solution

  • Iterator iterator = h1.iterator();
    if (iterator.hasNext()) {
        String firstElement = iterator.next();
    }