Skip to content

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 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 ||[0]) >= 0;
        previous_i[0] = i;
        return b; })
    .filter(b -> !b)

But this isn’t quite functional style.


  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.


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

Stream<String> stream2 ="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);



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 =;
    while(i.hasNext()) {
        T next =;
        if(current == null || current.compareTo(next) > 0) {
            return false;
        current = next;
    return true;
9 People found this is helpful