Skip to content
Advertisement

Are stream elements sorted? [closed]

Is there a way to find if the elements taken from a Stream in encounter order, are all sorted in ascending order? (The stream source could be absolutely anything, from Arrays.stream() to Files.lines(), for example; obviously, it would have to be an ordered stream.)

I was thinking of something like:

final Object[] previous_i = new Object[1];
boolean isSorted = stream
    .map(i -> {
        bool b = previous_i[0] == null || i.compare(previous_i[0]) >= 0;
        previous_i[0] = i;
        return b; })
    .filter(b -> !b)
    .findAny();

But this isn’t quite functional style.

Update:

  1. I’m not looking to sort the stream. Just to check if it’s already sorted.
  2. I’m not interested in seeing the elements of the stream. I only want to know if they’re already sorted. So it’s ok for this to be a terminal operation.
  3. The elements are objects (not primitives) and not null.

Examples:

Stream<String> stream1 = Arrays.stream("a", "b", "d", "c");
boolean isSorted1 = stream1.[answer...];
assert (!isSorted1);

Stream<String> stream2 = Arrays.stream("a", "b", "c", "d");
boolean isSorted2 = stream1.[answer...];
assert (isSorted2);

Stream<String> stream3 = java.nio.file.Files.lines(Path.of(fileWithRandomContent));
boolean isSorted3 = stream1.[answer...];
assert (!isSorted3);

Advertisement

Answer

Stream’s Iterator can be used for this as below:

public static <T extends Comparable<T>> boolean isSorted(Stream<T> stream) {
    Iterator<T> i = stream.iterator();
    if(!i.hasNext()) {
        return true;
    }
    T current = i.next();
    while(i.hasNext()) {
        T next = i.next();
        if(current == null || current.compareTo(next) > 0) {
            return false;
        }
        current = next;
    }
    return true;
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement