programing

반복기의 개수/길이/사이즈를 얻는 가장 좋은 방법은 무엇입니까?

sourcejob 2022. 12. 13. 20:06
반응형

반복기의 개수/길이/사이즈를 얻는 가장 좋은 방법은 무엇입니까?

'컴퓨팅'을 통해 리터레이터 수를 빠르게 얻을 수 있는 방법이 있습니까?

int i = 0;
for ( ; some_iterator.hasNext() ; ++i ) some_iterator.next();

...CPU 사이클의 낭비인 것 같습니다.

Guava 라이브러리 사용:

int size = Iterators.size(iterator);

내부적으로는 모든 요소에 걸쳐 반복되기 때문에 편리합니다.

만약 당신이 단지 반복기를 가지고 있다면, 그렇게 해야 합니다. 반복할 항목이 얼마나 남았는지 알 수 없기 때문에, 그 결과를 얻기 위해 질의할 수 없습니다.이를 효율적으로 실행할 수 있는 유틸리티 방법이 있습니다(예:Iterators.size()Guava)에서는 이 예시와 같이 반복기를 소비하고 계속 세고 있습니다.

그러나 대부분의 반복기는 컬렉션에서 제공되므로 크기를 쿼리할 수 있습니다.또한 사용자가 만든 클래스에서 반복기를 사용할 경우 해당 클래스에 size() 메서드를 제공할 수 있습니다.

, 반복기밖에 없는 상황에서는 더 나은 방법이 없지만, 대부분의 경우 크기를 직접 얻을 수 있는 기본 컬렉션이나 오브젝트에 액세스할 수 있습니다.

반복기 끝에 도달하면 코드가 예외를 부여합니다.다음과 같은 작업을 할 수 있습니다.

int i = 0;
while(iterator.hasNext()) {
    i++;
    iterator.next();
}

기본 컬렉션에 액세스할 수 있는 경우coll.size()...

편집 확인을 수정했습니다...

너는 항상 반복해야 할 것이다.그러나 Java 8, 9를 사용하여 상세하게 루프하지 않고 카운트를 수행할 수 있습니다.

Iterable<Integer> newIterable = () -> iter;
long count = StreamSupport.stream(newIterable.spliterator(), false).count();

다음은 테스트입니다.

public static void main(String[] args) throws IOException {
    Iterator<Integer> iter = Arrays.asList(1, 2, 3, 4, 5).iterator();
    Iterable<Integer> newIterable = () -> iter;
    long count = StreamSupport.stream(newIterable.spliterator(), false).count();
    System.out.println(count);
}

다음의 출력이 있습니다.

5

흥미로운 점은 여기서 카운트 조작을 병렬화할 수 있다는 것입니다.parallel이 콜의 플래그:

long count = StreamSupport.stream(newIterable.spliterator(), *true*).count();

Guava 라이브러리를 사용하는 또 다른 옵션은 다음과 같습니다.Iterable에 대해서List.

List list = Lists.newArrayList(some_iterator);
int count = list.size();

크기를 가져온 후 반복기의 요소에 액세스해야 하는 경우 이 옵션을 사용하십시오.사용방법Iterators.size()반복된 요소에 더 이상 액세스할 수 없습니다.

만약 당신이 가지고 있는 것이 반복기뿐이라면, "더 나은" 방법은 없습니다.만약 반복기가 컬렉션에서 나온다면 크기에 따라 그렇게 할 수 있습니다.

Iterator는 개별 값을 통과하기 위한 인터페이스일 뿐이므로 이와 같은 코드를 사용하는 것이 좋습니다.

    new Iterator<Long>() {
        final Random r = new Random();
        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public Long next() {
            return r.nextLong();
        }

        @Override
        public void remove() {
            throw new IllegalArgumentException("Not implemented");
        }
    };

또는

    new Iterator<BigInteger>() {
        BigInteger next = BigInteger.ZERO;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public BigInteger next() {
            BigInteger current = next;
            next = next.add(BigInteger.ONE);
            return current;
        }

        @Override
        public void remove() {
            throw new IllegalArgumentException("Not implemented");
        }
    }; 

만약 당신이 가지고 있는 것이 반복기뿐이라면, 더 효율적인 방법은 없습니다.또한 반복기를 한 번만 사용할 수 있는 경우 반복기의 내용을 얻기 전에 카운트를 얻는 것은 문제가 있습니다.

CollectionIterator...)

Java 8에서는 사용할 수 있습니다.

public static int getIteratorSize(Iterator iterator){
        AtomicInteger count = new AtomicInteger(0);
        iterator.forEachRemaining(element -> {
            count.incrementAndGet();
        });
        return count.get();
    }

반복할 수 있는 크기를 얻으려면

Iterable<Users> users = usersRepository.findUsersByLocation("IND");

이제 Type Itable 사용자 크기를 확인합니다.

assertEquals(2, ((Collection<Users>)users).size());

반복 개체에는 컬렉션에 포함된 것과 동일한 수의 요소가 포함되어 있습니다.

List<E> a =...;
Iterator<E> i = a.iterator();
int size = a.size();//Because iterators size is equal to list a's size.

그러나 반복기의 크기를 가져오고 인덱스 0을 통해 해당 크기로 반복하는 대신 반복기의 메서드 next()를 사용하여 반복하는 것이 좋습니다.

언급URL : https://stackoverflow.com/questions/9720195/what-is-the-best-way-to-get-the-count-length-size-of-an-iterator

반응형