Java Iterable Size iterableSizeEq(Iterable itrbl, int k)

Here you can find the source of iterableSizeEq(Iterable itrbl, int k)

Description

Checks whether the iterable itrbl has exactly k elements.

License

BSD License

Declaration

public static <E> boolean iterableSizeEq(Iterable<E> itrbl, int k) 

Method Source Code

//package com.java2s;
// Licensed under the Modified BSD Licence; see COPYING for details.

import java.util.Iterator;

public class Main {
    /** Checks whether the iterable <code>itrbl</code> has exactly
    <code>k</code> elements.  Instead of computing the length of
    <code>itrbl</code> (complexity: linear in the length) and
    comparing it with <code>k</code>, we try to iterate exactly
    <code>k</code> times and next check that <code>itrbl</code> is
    exhausted./*  w  w w  . j a  v a 2  s  . co  m*/
        
    Complexity: linear in <code>k</code>.  Hence, this test is
    very fast for small <code>k</code>s. */
    public static <E> boolean iterableSizeEq(Iterable<E> itrbl, int k) {
        // 1) try to iterate k times over itrbl;
        Iterator<E> it = itrbl.iterator();
        for (int i = 0; i < k; i++) {
            if (!it.hasNext())
                return false;
            it.next();
        }
        // 2) next check that there are no more elements in itrbl
        return !it.hasNext();
    }
}

Related

  1. getSingleElementOrNull(Iterable coll)
  2. getSingleIfExist(Iterable iterable)
  3. getSingleOrNull(Iterable iterable)
  4. iterableSize(Iterable iterable)
  5. iterableSize(Iterable itrbl)
  6. singleOrNull(Iterable iterable)
  7. singleOrNull(Iterable iterable)
  8. size(final Iterable iterable)
  9. size(final Iterable iterable)