ALABI Jesujoba ALABI Jesujoba - 4 months ago 9
Java Question

Giving Position to values in an ArrayList

i'm working on assigning positions to values in an arraylist in java.

For example An

ArrayList containing {5,6,3,1,9,10,0,2,6}
.

How can I correctly assign positions to the numbers to have something like this
{5th,3rd,7th 2nd,1st,8th, 6th,3rd}
.

I have successfully sorted the arraylist containing the numbers in java.

Am now stuck at giving position to the numbers.

Answer

So Would something like this work?

public static ArrayList<String> getPositions(ArrayList<Integer> list) {
    ArrayList<String> positions = new ArrayList<String>();
    String[] endings = { "th", "st", "nd", "rd" };
    Integer last = 100;
    Integer lastRank = 1;
    for (int index = 0; index < list.size(); index++) {
        int position = index + 1;
        if (last == list.get(index)) {
            position = lastRank;
        }
        int remainder = position % 10;
        String rank = position + "";
        if (remainder <= 3) {
            rank = rank + endings[remainder];
        } else {
            rank = rank + endings[0];
        }
        last = list.get(index);
        lastRank = position;
        positions.add(rank);
    }
    return positions;
}

I would also like to give credit to Robert van der Spek for coming up with a more efficient way to assign the ending of the position.