0

guys. I try to reverse a one-dim array using lambda in Java. while it doesn't work. Interestingly, it works for two-dim array. I was confused a lot. Could anyone help me with this? Thanks in advance.

Arrays.sort(arr, (n1, n2)->(n2 -n1));
# arr is a one-dim array
1
  • This will sort the array in descending order (assuming the elements are numerical). Short of shenanigans with mutable variables, you can't reverse an array in-place using sort (as it depends on the indices, not just the values) Commented Feb 20, 2022 at 21:42

2 Answers 2

1

If you do not have a restriction to only use sort, I have a contrived way to do an in place reversal using lambdas:

import java.util.Arrays;
import java.util.Collections;
import java.util.stream.IntStream;

public class ReverseArr {

    public static void main(String[] args) {
    Integer[] arr = { 4, 5, 61, 3, 9, 3, 1, -4, 7, 2, -8, 6, -3 };

    IntStream.rangeClosed(0, arr.length - 1)
             .boxed()
             .sorted(Collections.reverseOrder())
             .forEach(e -> {
                 if ((arr.length - e) - e > 1) {
                 int temp = arr[e];
                 arr[e] = arr[arr.length - e - 1];
                 arr[arr.length - e - 1] = temp;
                 }
             });

    Arrays.stream(arr)
          .forEach(e -> System.out.print(e+ " "));

    }

}

As the comment mentions, we have to do the reversal based on the indices. So I just generated those values and switch the values of arr using those indices through lambdas.

A key part is this condition: (arr.length - e) - e > 1. What it means is to stop reversing the elements once we get to the middle (the middle is when the difference is 1 if the array has an even number of elements and it is 0 if the array has an odd number of elements. This way we do not undo our reversal.

Output:

-3 6 -8 2 7 -4 1 3 9 3 61 5 4 
Sign up to request clarification or add additional context in comments.

Comments

1

To reverse 1-D array

  • Using Java 8 lambda

     IntStream.rangeClosed(1, arr.length)
           .mapToObj(i -> arr[arr.length - i])
           .toArray();
    
  • Using Collections.reverse() to reverse array

     Collections.reverse(arr);
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.