# Java program to replace each element by its rank in the given array

## Replace each element by its rank given in array

Here in this program we will learn  to replace each element by its rank in the given array which is discussed here. Given an array of distinct integers, we need to replace each element of the array with its rank. The minimum value element will have the highest rank in the Array.

## Example:

Input: {10,8.15.12,6,20,1}

Output: {4,3,6,5,2,7,1} ## Algorithm

A solution can be provided using maps.

The array element and its index are stored in two columns in the map and later the index is replaced by the element’s rank.

Step 1- Elements in a map will be stored in a sorted order, so on iterating it, the elements will be in an increasing order sequence.

Step 2- Give values for each element in increasing order starting from 1 to n, increment by 1 for each element.

## Java Code

```// Java program  to replace each element by its rank in the given array

import java.util.*;
import java.util.Map;
import java.util.TreeMap;

class PrepInsta
{
public static void transform(int[] arr)
{
Map<Integer, Integer> map = new TreeMap<>();

for (int j = 0; j < arr.l; j++) {
map.put(arr[j], j);
}

int rank = 1;

for (Map.Ent<Integer, Integer> ent : map.entSet()) {
arr[ent.getValue()] = rank++;
}
}

public static void main(String[] args)
{
int[] A = { 10, 8, 15, 12, 6, 20, 1 };

transform(A);

System.out.println(Arrays.toString(A));
}
}
```
```output
4, 3, 6, 5, 2, 7, 1

```