Stream sorted() leads to unexpected results

Viewed 384

I have an Array and a Stream like below.

String[] names = {"Alex", "Anna", "Abhi", "Some", "Broad", "Dustin", 
                  "amanda", "Hanna", "Steve", "Sydney"};
        
Stream.of(names)
        .sorted()
        .map(String::toLowerCase)
        .filter(x -> x.startsWith("a"))
        .forEachOrdered(System.out::println);
        //I have also tried - .forEach(System.out::println);

Actual Output:

abhi
alex
anna
amanda

Expected Output:

abhi
alex
amanda
anna

What am I missing here?

2 Answers

You are first sorting and only then applying the toLowerCase on the elements, and since Anna has capital A will come before amanda.

Do the following instead:

Stream.of(names)
        .map(String::toLowerCase)
        .filter(x -> x.startsWith("a"))
        .sorted()
        .forEachOrdered(System.out::println);

Output:

abhi
alex
amanda
anna

You are missing the .sorted() call before forEachOrdered, otherwise the contents of the stream will not be sorted after applying .toLowerCase().

What forEachOrdered does is run a function on every item in the stream in the order that they are in the stream; it does not sort the values themselves.

Related