Dom
Dom

Reputation: 159

Sort ArrayList in descending order

So I'm trying to sort my ArrayList from greatest to least. The user can only enter in numbers, which is then turned into a String. And that is all working very well, but when I display my scores I get something like this...

98
81
81
76
64
105
103
100

Anyone know how to make it sort...

105
103
100
98
81
81
76
64

Upvotes: 1

Views: 1282

Answers (3)

Fundhor
Fundhor

Reputation: 3577

Here is the code

    List<String> firstArrayList = new ArrayList<String>();
    firstArrayList.add("4"); // .add(readUSerInput());
    firstArrayList.add("30");
    firstArrayList.add("1");
    firstArrayList.add("02");

    ArrayList<Integer> newArrayList = new ArrayList<Integer>();

    for(String numero: firstArrayList){
        newArrayList.add(Integer.parseInt(numero));
    }

    newArrayList.sort(Collections.reverseOrder());

    // To check
    for(Integer numero: newArrayList){
        // use a Scanner() to print numero to the screen
    }

Upvotes: 2

Mureinik
Mureinik

Reputation: 310993

You are keeping the numbers as Strings and hence you are sorting them lexicographically ('9' comes after '1'). Instead, you should parse the strings to Integers (e.g., using Integer.valueOf) and stored in an ArrayList<Integer>. Now, when you sort it, the elements will be evaluated according to their numerical value.

Upvotes: 3

mbeintema
mbeintema

Reputation: 318

Dom - Keep in mind that a string is a bunch of chars, and each char has a integer value. Sorting strings !== sorting numbers.

Upvotes: 2

Related Questions