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
Which one is better here? iterator or stream?
Mkyong always works for me!