如何使用 Lambda 表达式对此进行排序? 我想对前 7 个数字进行排序并排除最后一个数字。我看到可以使用 IntStream.concat 但我需要使用 Lambda 表达式来排序。
Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());
最佳答案
“使用 lambda 表达式”的要求很奇怪。我只需将 .limit
调用替换为
.limit(((IntSupplier)() -> 8).getAsInt())
看!我在那里使用了 lambda ! () -> 8
。然后您可以按照您所说的那样继续使用 concat
对问题进行排序。
显然,这不是你的意思。
如果您想将 lambda 放入 sort
方法中对前 7 个整数进行排序,然后始终将第 8 个整数保留在末尾,您可以执行以下操作:
Random random = new Random();
List<Integer> unsorted = random.ints(1, 64)
.distinct()
.limit(8)
.boxed()
.collect(Collectors.toList());
// here you need to get the last element that you don't want to sort
int last = unsorted.get(unsorted.size() - 1);
// here is the lambda
List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
if (Integer.compare(x, y) == 0) {
return 0;
}
// if any one of the arguments is the last one...
if (last == x) {
return 1;
}
if (last == y) {
return -1;
}
return Integer.compare(x, y);
}).collect(Collectors.toList());
// you can also use "List.sort" with the same lambda
请注意,我个人认为这个sorted
方法调用非常不可读。乍一看,我看不出您正在尝试对除最后一个之外的所有内容进行排序。就可读性而言,使用concat
会更好。
关于java - 使用 Lambda 表达式对 List<Integer> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53195505/