Here you can find the source of iterableSizeEq(Iterable
itrbl
has exactly k
elements.
public static <E> boolean iterableSizeEq(Iterable<E> itrbl, int k)
//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(); } }