流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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。