How to Iterate over a Set/HashSet without an Iterator?

后端 未结 8 1989
闹比i
闹比i 2020-12-02 03:29

How can I iterate over a Set/HashSet without the following?

Iterator iter = set.iterator();
while (iter.hasNext()) {
    System.out         


        
相关标签:
8条回答
  • 2020-12-02 04:28

    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];
    
    0 讨论(0)
  • 2020-12-02 04:36

    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.}
    
    0 讨论(0)
提交回复
热议问题