Java Stream sorted(Comparator comparator)方法

Java Stream sorted(Comparator comparator)方法

Stream sorted(Comparator comparator) 返回一个由这个流的元素组成的流,根据 提供的比较器 进行排序 。 对于有序的流,排序方法是稳定的,但对于无序的流,不保证稳定性。它是一个 有状态的中间操作 ,也就是说,在处理新的元素时,它可能会结合之前看到的元素的状态。在java 8中,比较器可以使用lambda表达式进行实例化。我们还可以反转自然排序以及比较器提供的排序。
语法

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

其中,Stream是一个接口,T 是流元素的类型。比较器用于比较流元素。

下面给出了一些例子,以更好地理解该函数的实现。

例1 :

// Implementation of Stream.sorted()
// to get a stream of sorted elements
// according to the provided Comparator
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Integers
        List<Integer> list = Arrays.asList(5, -10, 7, -18, 23);
  
        System.out.println("The sorted stream according "
                           + "to provided Comparator is : ");
  
        // Displaying the list of Strings in
        // reverse order after sorting
        list.stream().sorted(Comparator.reverseOrder()).
                          forEach(System.out::println);
    }
}

输出:

The sorted stream according to provided Comparator is : 
23
7
5
-10
-18

例2 :

// Implementation of Stream.sorted()
// to get a stream of sorted elements
// according to the provided Comparator
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Strings
        List<String> list = Arrays.asList("Geeks", "for",
                    "GeeksforGeeks", "GeeksQuiz", "GFG");
  
        System.out.println("The sorted stream according "
                           + "to provided Comparator is : ");
  
        // Displaying the list of Strings in
        // reverse order after sorting
        list.stream().sorted(Comparator.reverseOrder()).
                            forEach(System.out::println);
    }
}

输出:

The sorted stream according to provided Comparator is : 
for
GeeksforGeeks
GeeksQuiz
Geeks
GFG

例3 :

// Implementation of Stream.sorted()
// to get a stream of sorted elements
import java.util.*;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating an array of Strings
        String[] array = { "GFG", "Geeks", "for",
                           "GeeksforGeeks", "GeeksQuiz" };
  
        System.out.println("The sorted stream is :");
  
        // sorting the elements of array based
        // on their last character
        Stream.of(array).sorted((str1, str2)
                     -> Character.compare(str1
                     .charAt(str1.length() - 1),
                    str2.charAt(str2.length() - 1)))
            .         forEach(System.out::println);
    }
}

输出:

The sorted stream is :
GFG
for
Geeks
GeeksforGeeks
GeeksQuiz

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程