Main Tutorials

Java – How to get the first item from Set

In Java, we can use Set.iterator().next() to get the first item from a java.util.Set

JavaExample.java

package com.mkyong;

import java.util.HashSet;
import java.util.Set;

public class JavaExample {

    public static void main(String[] args) {

        Set<String> examples = new HashSet<>();
        examples.add("1");
        examples.add("2");
        examples.add("3");
        examples.add("4");
        examples.add("5");

        System.out.println(examples.iterator().next());

        // java 8
        System.out.println(examples.stream().findFirst().get());
    }

}

Output


1
1

References

  1. Oracle doc – Set

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Shiva
4 years ago

Which one is better here? iterator or stream?

Khan
3 years ago

Mkyong always works for me!