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. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Shiva Recent comment authors
newest oldest most voted
Shiva
Guest
Shiva

Which one is better here? iterator or stream?