Java8中,可以通过流的sorted操作对流中的元素排序,sorted操作的参数是Comparator接口,通过传入一个比较函数来实现排序操作,最直接的,就是通过形如
(a, b) -> { int n = Math.min(a.size(), b.size()); for (int i = 0; i < n; i++) { if (a.get(i) > b.get(i)) { return 1; } else if (a.get(i) < b.get(i)) { return -1; } } return 0; }
这样的lambda表达式来实现,当a>b时,返回一个正数,a<b时,返回一个负数,a=b时,返回0(Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.),比较的逻辑写在lambda表达式中,灵活、方便、高效。如果流中的数据还需要再做一些处理再比较,可以通过Comarator.comparing中的第一个参数,Function<? super T, ? extends U> keyExtractor来处理。例如:
Comparator.comparing(k -> k, (a, b) -> { int n = Math.min(a.size(), b.size()); for (int i = 0; i < n; i++) { if (a.get(i) > b.get(i)) { return 1; } else if (a.get(i) < b.get(i)) { return -1; } } return 0; })
代码示例:
import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; public class StreamSortedTest { public static void main(String[] args) { List<List<Integer>> data = new ArrayList<>(); data.add(Arrays.asList(1, 1, 1, 1, 1)); data.add(Arrays.asList(1, 1, 1, 2)); data.add(Arrays.asList(5)); data.add(Arrays.asList(1, 2, 2)); data.add(Arrays.asList(1, 4)); data.add(Arrays.asList(2, 3)); data.add(Arrays.asList(1, 1, 3)); data.forEach(System.out::println); System.out.println("-----------------------"); data.stream().sorted((a, b) -> { int n = Math.min(a.size(), b.size()); for (int i = 0; i < n; i++) { if (a.get(i) > b.get(i)) { return 1; } else if (a.get(i) < b.get(i)) { return -1; } } return 0; }).forEach(System.out::println); System.out.println("-----------------------"); data.stream().sorted(Comparator.comparing(k -> k, (a, b) -> { int n = Math.min(a.size(), b.size()); for (int i = 0; i < n; i++) { if (a.get(i) > b.get(i)) { return 1; } else if (a.get(i) < b.get(i)) { return -1; } } return 0; })).forEach(System.out::println); } }
打印输出:
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[5]
[1, 2, 2]
[1, 4]
[2, 3]
[1, 1, 3]
-----------------------
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]
-----------------------
[1, 1, 1, 1, 1]
[1, 1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 4]
[2, 3]
[5]
Process finished with exit code 0
标签:return,Comparator,Stream,get,int,comparator,Arrays,data,size From: https://www.cnblogs.com/songshijia88888/p/16786573.html