-2

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Anish
  • 155
  • 1
  • 13

2 Answers2

1

A safe approach would be to stream it and use findFirst():

Object first = h1.stream().findFirst().orElse(null);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
-1
Iterator iterator = h1.iterator();
if (iterator.hasNext()) {
    String firstElement = iterator.next();
}