[java] 반복자없이 Set / HashSet을 반복하는 방법?

다음없이 Set/ HashSet를 반복하는 방법은 무엇입니까?

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



답변

향상된 for 루프를 사용할 수 있습니다 .

Set<String> set = new HashSet<String>();

//populate set

for (String s : set) {
    System.out.println(s);
}

또는 Java 8 :

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


답변

집합을 반복하는 추가 방법은 6 가지 이상 있습니다. 다음은 나에게 알려져 있습니다.

방법 1

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

방법 2

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

방법 3

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

방법 4

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

방법 5

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

방법 6

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

이것은 HashSet내 예제에 사용한 것입니다.

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


답변

집합을 배열로 변환
하면 요소를 반복하는 데 도움이 될 수 있습니다.

Object[] array = set.toArray();

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


답변

시연을 위해 다른 Person 객체를 보유하는 다음 세트를 고려하십시오.

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

개인 모델 클래스

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. for 문은 Collections and arrays를 통한 반복을 위해 설계된 양식을 가지고 있습니다.
for(Person p:people){
  System.out.println(p.getName());
}
  1. Java 8-java.lang.Iterable.forEach (소비자)
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


답변

보다 깔끔한 코드를 위해 기능적 작업을 사용할 수 있습니다

Set<String> set = new HashSet<String>();

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


답변

다음은 퍼포먼스와 함께 세트를 반복하는 방법에 대한 팁입니다.

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

코드는 자명하다.

지속 시간의 결과는 다음과 같습니다.

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

Lambda가장 오래 걸리는 것이 가장 Iterator빠르다는 것을 알 수 있습니다 .


답변

열거(?):

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

다른 방법 (java.util.Collections.enumeration ()) :

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

자바 8 :

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

또는

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