key at
key at

Reputation: 11

Why java Stream.sorted() gives different result?

That's my code:

@Test
public void testStream() {
    List<String> list = Arrays.asList("I", "love", "you", "too");
    Collections.sort(list, (s1, s2) -> {
        if (s1 == null)
            return -1;
        if (s2 == null)
            return 1;
        return s1.length() - s2.length();
    });
    list.stream().sorted().forEach(System.out::println);
    list.forEach(l -> {
        System.out.println(l);
    });
}

And the result is:

{I,love,too,you}
{I,you,too,love}

I learned that forEach() is a terminal operation and the right order is last one?

Upvotes: 0

Views: 115

Answers (1)

Amadan
Amadan

Reputation: 198324

.sorted() with no parameters gives you natural order. However, you give a length comparator to Collections.sort.

Thus, the first line is sorted alphabetically, but the second is sorted lengthwise — exactly as you requested.

If you passed the same comparator to .sorted(...), you would get the same result.

Upvotes: 2

Related Questions