流sorted()返回由该流的元素组成的流,并根据自然顺序对其进行排序。对于有序流,sort方法是稳定的,但对于无序流,则不能保证稳定性。这是有状态的中间操作,即在处理新元素时,它可以合并先前看到的元素的状态。
用法:
StreamT> sorted() Where, Stream is an interface and T is the type of stream elements.
异常:如果此流的元素不可比较,则在执行终端操作时可能会引发java.lang.ClassCastException。
下面给出一些示例,以更好地理解该函数的实现。
范例1:
// Implementation of Stream.sorted()
// to get a stream of elements
// sorted in their natural order
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of integers
List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);
System.out.println("The sorted stream is:");
// displaying the stream with elements
// sorted in natural order
list.stream().sorted().forEach(System.out::println);
}
}
输出:
The sorted stream is: -18 -9 0 4 25
范例2:
// Implementation of Stream.sorted()
// to get a stream of elements
// sorted in their natural order
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of strings
List<String> list = Arrays.asList("Geeks", "for",
"GeeksQuiz", "GeeksforGeeks", "GFG");
System.out.println("The sorted stream is:");
// displaying the stream with elements
// sorted in their natural order
list.stream().sorted().forEach(System.out::println);
}
}
输出:
The sorted stream is: GFG Geeks GeeksQuiz GeeksforGeeks for
范例3:
// Using stream sorted to sort a stream
// of user defined class objects
import java.util.*;
class Point
{
Integer x, y;
Point(Integer x, Integer y) {
this.x = x;
this.y = y;
}
public String toString() {
return this.x + ", "+ this.y;
}
}
class GFG
{
public static void main(String[] args)
{
List<Point> aList = new ArrayList<>();
aList.add(new Point(10, 20));
aList.add(new Point(5, 10));
aList.add(new Point(1, 100));
aList.add(new Point(50, 2000));
// displaying the stream with elements
// sorted according to x coordinate
aList.stream()
.sorted((p1, p2)->p1.x.compareTo(p2.x))
.forEach(System.out::println);
}
}
输出:
1, 100 5, 10 10, 20 50, 2000
相关用法
- Java Stream sorted(Comparator comparator)用法及代码示例
- Java Stream.of()和Arrays.stream()的区别用法及代码示例
- Java Stream of()用法及代码示例
- Java Stream map()用法及代码示例
- Java Stream.concat()用法及代码示例
- Java Set转Stream用法及代码示例
- Java Stream转Set用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream sorted() in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。