[英]Java: sorting an array with lambda expression?
I've recently got into functional programming and Java 8 lambdas. 我最近进入了函数式编程和Java 8 lambdas。 I have an array of ints and I want to sort it in an ascending order. 我有一组int,我想按升序排序。
The way I am trying to do this with lambda is as follows: 我试图用lambda做的方式如下:
Arrays.stream(intArray).sorted((x, y) -> Integer.compare(x, y) == -1);
The issue with this is that my compiler says: 这个问题是我的编译器说:
Error:(12, 32) java: method sorted in interface
java.util.stream.IntStream cannot be applied to given types;
required: no arguments
found: (x,y)->Int[...]== -1
reason: actual and formal argument lists differ in length
What am I missing here? 我在这里错过了什么?
A Comparator
takes two Object
and returns an int
. Comparator
接受两个Object
并返回一个int
。
Here, we're entering with two Object
's but are returning a boolean expression ( Integer.compare(x, y) == -1
) 在这里,我们输入两个Object
,但返回一个布尔表达式( Integer.compare(x, y) == -1
)
You actually just need the first part of it 你实际上只需要它的第一部分
Arrays.stream(intArray)
.sorted((x, y) -> Integer.compare(x, y))
.toArray(Integer[]::new);
Since you seem to be using an array of Integer
objects (because an IntStream
doesn't have a sorted(Comparator)
method) you better be using a simple IntStream
, it will simplify your life because the int
will than be sorted in their natural order. 由于您似乎使用了一个Integer
对象数组(因为IntStream
没有sorted(Comparator)
方法),您最好使用一个简单的IntStream
,它将简化您的生活,因为int
将按其自然顺序排序。
IntStream#sorted()
Returns a stream consisting of the elements of this stream in sorted order. 以排序顺序返回由此流的元素组成的流。
Arrays.stream(intArray)
.mapToInt(x->x)
.sorted()
.toArray();
You can do 你可以做
Arrays.stream(intArray).sorted().forEach(System.out::println);
The error in your case is because IntStream#sorted()
does not take parameters. 您的情况中的错误是因为IntStream#sorted()
不接受参数。
Arrays.stream(intArray).sorted()
Should be used for processing the array in a specific order. Arrays.stream(intArray).sorted()
应该用于按特定顺序处理数组。 It can be used to sort arrays as explained in other answers but it will generate a new sorted array. 它可以用于对数组进行排序,如其他答案中所述,但它将生成一个新的排序数组。
Arrays.stream(intArray)
.sorted((x, y) -> Integer.compare(x, y))
.toArray(Integer[]::new);
In case of very big sized data this will not be efficient. 如果数据量非常大,则效率不高。
If you want to do in-place sorting, you can use Collections.sort() 如果要进行就地排序,可以使用Collections.sort()
Arrays.sort(arr, (x,y) -> Integer.compare(x,y))
Or in the case of objects of type A and sorting based on field P 或者在类型A的对象和基于字段P的排序的情况下
Arrays.sort(arr, Comparator.comparing(A::getP))
where getP() is the method that gets the field P value. 其中getP()是获取字段P值的方法。
In case of reversed sorting 在反向排序的情况下
Arrays.sort(arr, Comparator.comparing(A::getP).reversed())
In case of sorting on 2 fields P and P2 如果在2个字段P和P2上排序
Arrays.sort(arr, Comparator.comparing(A::getP).thenComparing(A::getP2))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.