Close

Java 8 Streams - Stream.sorted Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Methods:

Stream<T> sorted()

This stateful intermediate operation returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.



Stream<T> sorted(Comparator<? super T> comparator)

Similar to above method but the elements of this stream are sorted according to the provided Comparator.


Examples


package com.logicbig.example.stream;

import java.util.stream.Stream;

public class SortedExample {
//Stream<T> sorted()

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};

System.out.println("-- sequential --");
Stream.of(s)
.sorted()
.forEach(System.out::println);

System.out.println("-- parallel --");
Stream.of(s)
.parallel()
.sorted()
.forEach(System.out::println);
}
}

Output

-- sequential --
four
one
three
two
-- parallel --
three
four
two
one




Sorting by last char, using a custom comparator

package com.logicbig.example.stream;

import java.util.stream.Stream;

public class SortedExample2 {

public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};

Stream.of(s)
.sorted((a, b) ->
Character.compare(a.charAt(a.length() - 1),
b.charAt(b.length() - 1)))
.forEach(System.out::println);
}
}

Output

one
three
two
four




Stream.sorted(), IntStream.sorted(), LongStream.sorted() and DoubleStream.sorted() rearrange the stream elements in natural order. They discard the original encounter order (if there's any). For a customized sorting use equivalent sorted(Comparator) methods.

package com.logicbig.example;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.IntStream;

public class SortedExample {

public static void main (String[] args) {
Set<Integer> list = new HashSet<>(Arrays.asList(2, 1, 3));
Object[] objects = list.stream().sorted().toArray();
System.out.println(Arrays.toString(objects));
}
}

Output

[1, 2, 3]
Original Post




See Also