如何使用Lambda表达式对此进行排序?我应该对前7个数字进行排序,并排除最后一个数字。我看到可以使用IntStream.concat,但我需要使用Lambda表达式进行排序。
Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());
发布于 2018-11-07 11:04:46
“使用lambda表达式”的要求非常奇怪。我只需将.limit
调用替换为
.limit(((IntSupplier)() -> 8).getAsInt())
看!我在那儿用过灯!() -> 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
会更好。
发布于 2018-11-07 11:09:01
您可以使用lambda作为Collections.sort()
的第二个参数,提供子列表作为第一个参数:
Collections.sort(lucky.subList(0, lucky.size()-1),
(i1, i2) -> i1.compareTo(i2));
这相当于Collections.sort(lucky.subList(0, lucky.size()-1))
,所以这里并不需要这个lambda表达式。
另一种方法(不是有效的)是使用Stream.concat()
List<Integer> sorted = Stream.concat(
lucky.stream()
.filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
Stream.of(lucky.get(lucky.size() - 1)))
.collect(Collectors.toList());
注意,我是根据值而不是索引过滤第一个流中的项,因为lucky
列表中的项是不同的。这可以在索引的基础上完成,尽管这会使排序的性能更差。
https://stackoverflow.com/questions/53195505
复制相似问题