Sollicitatievraag bij LinkedIn

filteriterator hasnext() and next() function

Antwoord op sollicitatievraag

Anoniem

18 jan 2014

public class FilterIterator { private Predicate pred; private Iterator iter; private T cachedNext; private boolean hasCached = false; FilterIterator(Iterator i, Predicate p) { iter = i; pred = p; } public boolean hasNext() { if (hasCached) return true; while (iter.hasNext()) { T tmp = iter.next(); if (pred.evaluate(tmp)) { setCache(tmp); break; } } return hasCached; } public T next() { if (! hasNext()) throw new NoSuchElementException(); return getCache(); } private T getCache() { hasCached = false; return cachedNext; } private void setCache(T tmp) { hasCached = true; cachedNext = tmp; } public static void main(String [] args) { List ls = Arrays.asList("Test", "Hello", "World", "This is a long string"); FilterIterator fi = new FilterIterator(ls.iterator(), new Predicate() { public boolean evaluate(String elem) { return elem.length() > 5; } }); while(fi.hasNext()) { System.out.println(fi.next()); } } }