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 the Author

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

Comments

avatar