How can I iterate over a Set
/HashSet
without the following?
Iterator iter = set.iterator();
while (iter.hasNext()) {
System.out
Converting your set into an array may also help you for iterating over the elements:
Object[] array = set.toArray();
for(int i=0; i<array.length; i++)
Object o = array[i];
However there are very good answers already available for this. Here is my answer:
1. set.stream().forEach(System.out::println); // It simply uses stream to display set values
2. set.forEach(System.out::println); // It uses Enhanced forEach to display set values
Also, if this Set is of Custom class type, for eg: Customer.
Set<Customer> setCust = new HashSet<>();
Customer c1 = new Customer(1, "Hena", 20);
Customer c2 = new Customer(2, "Meena", 24);
Customer c3 = new Customer(3, "Rahul", 30);
setCust.add(c1);
setCust.add(c2);
setCust.add(c3);
setCust.forEach((k) -> System.out.println(k.getId()+" "+k.getName()+" "+k.getAge()));
// Customer class:
class Customer{
private int id;
private String name;
private int age;
public Customer(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} // Getter, Setter methods are present.}