Java: sorting an array with lambda expression?

百般思念 提交于 2021-02-07 09:16:11

问题


I've recently got into functional programming and Java 8 lambdas. I have an array of ints and I want to sort it in an ascending order.

The way I am trying to do this with lambda is as follows:

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?


回答1:


A Comparator takes two Object and returns an int.

Here, we're entering with two Object's but are returning a boolean expression (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.

IntStream#sorted()

Returns a stream consisting of the elements of this stream in sorted order.

Arrays.stream(intArray)
      .mapToInt(x->x)
      .sorted()
      .toArray();



回答2:


You can do

Arrays.stream(intArray).sorted().forEach(System.out::println);  

The error in your case is because IntStream#sorted() does not take parameters.

DEMO




回答3:


Arrays.stream(intArray).sorted() Should be used for processing the array in a specific order. 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()

Arrays.sort(arr, (x,y) -> Integer.compare(x,y))

Or in the case of objects of type A and sorting based on field P

Arrays.sort(arr, Comparator.comparing(A::getP))

where getP() is the method that gets the field P value.

In case of reversed sorting

 Arrays.sort(arr, Comparator.comparing(A::getP).reversed())

In case of sorting on 2 fields P and P2

Arrays.sort(arr, Comparator.comparing(A::getP).thenComparing(A::getP2))


来源:https://stackoverflow.com/questions/36370658/java-sorting-an-array-with-lambda-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!