Ajay Kumar
Ajay Kumar

Reputation: 3250

Stream sorted() leads to unexpected results

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?

Upvotes: 6

Views: 979

Answers (2)

dreamcrash
dreamcrash

Reputation: 51413

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

Upvotes: 16

Billy Brown
Billy Brown

Reputation: 2342

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.

Upvotes: 5

Related Questions