Kobek
Kobek

Reputation: 1211

Java: sorting an array with lambda expression?

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?

Upvotes: 3

Views: 10066

Answers (3)

Mohamed Gad-Elrab
Mohamed Gad-Elrab

Reputation: 646

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))

Upvotes: 1

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

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();

Upvotes: 5

singhakash
singhakash

Reputation: 7919

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

Upvotes: 3

Related Questions