All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.commons.sequence.SortedSequence Maven / Gradle / Ivy

There is a newer version: 12.0.2
Show newest version
package net.dongliu.commons.sequence;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Objects;

/**
 * A lazy sorted Sequence implementation
 */
class SortedSequence implements Sequence {
    private Sequence original;
    private final Comparator comparator;

    private Sequence delegate = null;

    SortedSequence(Sequence original, Comparator comparator) {
        this.original = original;
        this.comparator = comparator;
    }


    @Override
    public boolean hasNext() {
        if (delegate == null) {
            if (!original.hasNext()) {
                return false;
            }
            ArrayList list = original.toArrayList();
            if (list.size() == 1) {
                // check if element is illegal for sort ASAP.
                Comparator value = (Comparator) Objects.requireNonNull(list.get(0));
                delegate = Sequence.of(list.get(0));
            } else {
                list.sort(comparator);
                delegate = Sequence.of(list);
            }
            original = null;
        }

        return delegate.hasNext();
    }

    @Override
    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return delegate.next();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy