Similar to above method but the elements of this stream are sorted according to the provided Comparator
.
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