Filter the list of items in a lazy way

I have a list of objects, and I want to create another list that will include only objects for which the method acceptable()returns "true". My problem is that I want to make this choice only on demand. In other words, I want the new list to be computed and populated only when its method is iterator()called. Are there libraries for Java?

I am using JDK7

+4
source share
4 answers

Guava has many helper methods for this type of function. What you want is already implemented.

Iterators.filter if you want to cross Iterator from collection.

Iterables.filter, Iterable, , " ".

Collections2.filter, , .

+4

Java 8:

List<YourClass> list = ...;

Stream<YourClass> filteredList = list.filter(YourClass::acceptable());

, , , .

+1

, , - , - :

public class ResolveList<T extends MyClass> implements Iterable<T> {
//T extends MyClass for access to MyClass.acceptable()
    private final List<T> rawList;
    private List<T> processedList;
    public List<T> getList() {
        if(processedList == null) {
            processList();
        }
        return processedList; //check if null
    }

    public ResolveList(List<T> list) {
        this.rawList = list;
    }

    private void processList() {
        processedList = new ArrayList<T>(); //or whatever kind of list you prefer.
        for(T t : rawList) {
            if(t.acceptable()) {
                processedList.add(t);
            }
        }
    }

    @Override
    public Iterator<T> iterator() {
        return this.getList().iterator();
    }
}

. getList() List<> .

+1

, , . LazyIterator:

public class LazyIterator<E extends Acceptable> implements Iterator<E> {
    private final Iterator<E> iterator;
    private boolean hasNext;
    private E next;

    public LazyIterator(Iterator<E> iterator) {
        this.iterator = iterator;
        iterate();
    }

    private void iterate() {
        hasNext = false;
        while (iterator.hasNext()) {
            next = iterator.next();
            if (next.accept()) {
                hasNext = true;
                break;
            }
        }
    }

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

    @Override public E next() {
        if (!hasNext) throw new NoSuchElementException();
        E out = next;
        iterate();
        return out;
    }

    @Override public void remove() { throw new RuntimeException("N/A"); }
}

LazyIterable

public class LazyIterable<E extends Acceptable> implements Iterable<E> {

    private final Iterable<E> wrapped;

    public LazyIterable(Iterable<E> wrapped) {
        this.wrapped = wrapped;
    }

    @Override
    public Iterator<E> iterator() {
        return new LazyIterator<E>(wrapped.iterator());
    }
}

.

+1

All Articles