Hoe een set/hashset herhalen zonder een iterator?

Hoe kan ik een Set/HashSetherhalen zonder het volgende?

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

Antwoord 1, autoriteit 100%

Je kunt een verbeterde for-lusgebruiken:

Set<String> set = new HashSet<String>();
//populate set
for (String s : set) {
    System.out.println(s);
}

Of met Java 8:

set.forEach(System.out::println);

Antwoord 2, autoriteit 21%

Er zijn ten minste zes extra manieren om een set te herhalen. De volgende zijn mij bekend:

Methode 1

// Obsolete Collection
Enumeration e = new Vector(movies).elements();
while (e.hasMoreElements()) {
  System.out.println(e.nextElement());
}

Methode 2

for (String movie : movies) {
  System.out.println(movie);
}

Methode 3

String[] movieArray = movies.toArray(new String[movies.size()]);
for (int i = 0; i < movieArray.length; i++) {
  System.out.println(movieArray[i]);
}

Methode 4

// Supported in Java 8 and above
movies.stream().forEach((movie) -> {
  System.out.println(movie);
});

methode 5

// Supported in Java 8 and above
movies.stream().forEach(movie -> System.out.println(movie));

methode 6

// Supported in Java 8 and above
movies.stream().forEach(System.out::println);

Dit is de HashSetdie ik heb gebruikt voor mijn voorbeelden:

Set<String> movies = new HashSet<>();
movies.add("Avatar");
movies.add("The Lord of the Rings");
movies.add("Titanic");

Antwoord 3, Autoriteit 5%

Converteren van uw set in een array
kan u ook helpen bij het herhalen van de elementen:

Object[] array = set.toArray();
for(int i=0; i<array.length; i++)
   Object o = array[i];

Antwoord 4, Autoriteit 3%

Overweeg de volgende set, die verschillende persoonsobjecten bevat:

Set<Person> people = new HashSet<Person>();
people.add(new Person("Tharindu", 10));
people.add(new Person("Martin", 20));
people.add(new Person("Fowler", 30));

Model klasse

public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //TODO - getters,setters ,overridden toString & compareTo methods
}
  1. De voorrekening heeft een formulier dat is ontworpen voor iteratie via collecties en arrays. Deze vorm wordt soms de versterkte verklaring genoemd en kan worden gebruikt om uw lussen compacter en gemakkelijk te lezen te maken.
for(Person p:people){
  System.out.println(p.getName());
}
  1. JAVA 8 – JAVA.LANG.ITELABLE.FOREACH (Consument)
people.forEach(p -> System.out.println(p.getName()));
default void forEach(Consumer<? super T> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller. Implementation Requirements:
The default implementation behaves as if: 
for (T t : this)
     action.accept(t);
Parameters: action - The action to be performed for each element
Throws: NullPointerException - if the specified action is null
Since: 1.8

Antwoord 5, Autoriteit 2%

U kunt functionele bediening gebruiken voor een meer nette code

Set<String> set = new HashSet<String>();
set.forEach((s) -> {
     System.out.println(s);
});

Antwoord 6, Autoriteit 2%

Hier zijn enkele tips over het herheren van een set samen met hun uitvoeringen:

public class IterateSet {
    public static void main(String[] args) {
        //example Set
        Set<String> set = new HashSet<>();
        set.add("Jack");
        set.add("John");
        set.add("Joe");
        set.add("Josh");
        long startTime = System.nanoTime();
        long endTime = System.nanoTime();
        //using iterator
        System.out.println("Using Iterator");
        startTime = System.nanoTime();
        Iterator<String> setIterator = set.iterator();
        while(setIterator.hasNext()){
            System.out.println(setIterator.next());
        }
        endTime = System.nanoTime();
        long durationIterator = (endTime - startTime);
        //using lambda
        System.out.println("Using Lambda");
        startTime = System.nanoTime();
        set.forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationLambda = (endTime - startTime);
        //using Stream API
        System.out.println("Using Stream API");
        startTime = System.nanoTime();
        set.stream().forEach((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationStreamAPI = (endTime - startTime);
        //using Split Iterator (not recommended)
        System.out.println("Using Split Iterator");
        startTime = System.nanoTime();
        Spliterator<String> splitIterator = set.spliterator();
        splitIterator.forEachRemaining((s) -> System.out.println(s));
        endTime = System.nanoTime();
        long durationSplitIterator = (endTime - startTime);
        //time calculations
        System.out.println("Iterator Duration:" + durationIterator);
        System.out.println("Lamda Duration:" + durationLambda);
        System.out.println("Stream API:" + durationStreamAPI);
        System.out.println("Split Iterator:"+ durationSplitIterator);
    }
}

De code spreekt voor zich.

Het resultaat van de duur is:

Iterator Duration: 495287
Lambda Duration: 50207470
Stream Api:       2427392
Split Iterator:    567294

We kunnen zien dat de Lambdahet langst duurt, terwijl Iteratorhet snelst is.


Antwoord 7

Opsomming(?):

Enumeration e = new Vector(set).elements();
while (e.hasMoreElements())
    {
        System.out.println(e.nextElement());
    }

Een andere manier (java.util.Collections.enumeration()):

for (Enumeration e1 = Collections.enumeration(set); e1.hasMoreElements();)
    {
        System.out.println(e1.nextElement());
    }

Java 8:

set.forEach(element -> System.out.println(element));

of

set.stream().forEach((elem) -> {
    System.out.println(elem);
});

Antwoord 8

Er zijn hier echter al hele goede antwoorden voor. Hier is mijn antwoord:

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

Ook als deze Set van het type Aangepast is, bijvoorbeeld: Klant.

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()));

// Klantklasse:

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.}

Other episodes