📜  Java中的流排序(比较器比较器)方法

📅  最后修改于: 2022-05-13 01:54:32.440000             🧑  作者: Mango

Java中的流排序(比较器比较器)方法

Stream sorted(Comparator compare)返回一个由该流的元素组成的流,根据提供的 Comparator进行排序。对于有序流,排序方法是稳定的,但对于无序流,不能保证稳定性。它是一个有状态的中间操作,即在处理新元素时,它可以合并来自先前看到的元素的状态。在Java 8 中,Comparator 可以使用 lambda 表达式来实例化。我们还可以反转自然排序以及 Comparator 提供的排序。
句法 :

Stream sorted(Comparator comparator)

Where, Stream is an interface and T
is the type of stream elements.
comparator is used to compare stream elements.

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

示例 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 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 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