Shiva Nandam - 4 months ago 51

Java Question

**print the absolute sorted array. See the sample output for clarification.**

**Input:**

`9 -2 10 3 -5 34 -22 7`

`-2 3 -5 7 9 10 -22 34`

I was tried with

`Arrays.sort(a[]);`

please help me out:

Thank you

Answer

With Java 8, you can use lamda and Math.abs like this:

```
Integer[] array = {9,-2,10,3,-5,34,-22,7};
Arrays.sort(array, (a,b) -> (Integer.compare( Math.abs(a), Math.abs(b))));
Stream.of(array).forEach(a -> System.out.println(a));
```

Thanks to 4castle for suggestion. Or use Comparator

```
Arrays.sort(array, Comparator.comparingInt(Math::abs));
```