Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an efficient Java 8 sorted Spliterator from an array

In Java 8, a variety of convenient utilities are provided to build efficient Spliterators from arrays. However, no factory methods are provided there to build a Spliterator with a comparator. Clearly Spliterators are allowed to have attached comparators; they have a getComparator() method and a SORTED property.

How are library authors supposed to build SORTED Spliterators?

like image 896
Louis Wasserman Avatar asked Nov 19 '13 15:11

Louis Wasserman


1 Answers

It seems that it is not foreseen to have such a Spliterator with an order other than natural. But implementing it is not that hard. It could look like this:

class MyArraySpliterator implements Spliterator.OfInt {
    final int[] intArray;
    int pos;
    final int end;
    final Comparator<? super Integer> comp;

    MyArraySpliterator(int[] array, Comparator<? super Integer> c) {
        this(array, 0, array.length, c);
    }
    MyArraySpliterator(int[] array, int s, int e, Comparator<? super Integer> c) {
        intArray=array;
        pos=s;
        end=e;
        comp=c;
    }
    @Override
    public OfInt trySplit() {
        if(end-pos<64) return null;
        int mid=(pos+end)>>>1;
        return new MyArraySpliterator(intArray, pos, pos=mid, comp);
    }
    @Override
    public boolean tryAdvance(IntConsumer action) {
        Objects.requireNonNull(action);
        if(pos<end) {
            action.accept(intArray[pos++]);
            return true;
        }
        return false;
    }
    @Override
    public boolean tryAdvance(Consumer<? super Integer> action) {
        Objects.requireNonNull(action);
        if(pos<end) {
            action.accept(intArray[pos++]);
            return true;
        }
        return false;
    }
    @Override
    public long estimateSize() {
        return end-pos;
    }
    @Override
    public int characteristics() {
        return SIZED|SUBSIZED|SORTED|ORDERED|NONNULL;
    }
    @Override
    public Comparator<? super Integer> getComparator() {
        return comp;
    }
}

But Java 8 is not entirely fixed yet. Maybe there will be a JRE-provided solution in the final.

like image 55
Holger Avatar answered Oct 20 '22 04:10

Holger