9

i have a string array consisting of a name and a score. I want to sort that array by score. Problem is, considering it's a string array, the scores are strings which results in 13,16,2,5,6 and not 2,5,6,13,16. I am using this code:

int spaceIndex;
String[][] scoreboard;
String[] playername;
String[] score;
int sbsize;

array1.add("Thomas" + ":" + 5);
array1.add("Blueb" + ":" + 6);
array1.add("James" + ":" + 16);
array1.add("Hleb" + ":" + 13);
array1.add("Sabbat" + ":" + 2);
sbsize = array1.size();
scoreboard = new String[sbsize][2];
playername = new String[sbsize];
score = new String[sbsize];
pos2 = new int[sbsize];

for (int i=0; i<array1.size(); i++)
{
    spaceIndex =  array1.get(i).indexOf(':'); 
    scoreboard[i][0] = array1.get(i).substring(0, spaceIndex);
    scoreboard[i][1] = array1.get(i).substring(spaceIndex+1, array1.get(i).length());
}

Arrays.sort(scoreboard, new Comparator<String[]>() {
 @Override
 public int compare(String[] entry1, String[] entry2) {
    String time1 = entry1[1];
    String time2 = entry2[1];
    return time1.compareTo(time2);
    }
 });

What is the solution?

2
  • If that's score, why not store it in integer? OK, even not store in integer, you can cast it to integer and compare. Commented Jun 3, 2011 at 9:01
  • needful url to sort arry mkyong.com/java/how-to-sort-an-array-in-java Commented Aug 5, 2015 at 7:26

8 Answers 8

19

Cast them to int. As I recall, something like...

Arrays.sort(scoreboard, new Comparator<String[]>() {
     @Override
     public int compare(String[] entry1, String[] entry2) {
        Integer time1 = Integer.valueOf(entry1[1]);
        Integer time2 = Integer.valueOf(entry2[1]);
        return time1.compareTo(time2);
        }
     });

Also you can make simple value object class for easier manipulations. Like...

class Player
{
  public String name;
  public int score;
}

And after that you can make

 Player[] scoreboard = ...
 Arrays.sort(scoreboard, new Comparator<Player>() {
          @Override
          public int compare(Player player1, Player player2) {
              if(player1.score > player2.score) return 1;
              else if(player1.score < player2.score) return -1;
              else return 0;            
             }
 });

Edit: I recommend you to understand the basic OOP principles, this will help you a lot in the beginning.

Edit 2: Java 8 (with functional interface and a lambda):

Arrays.sort(scoreboard, (player1, player2) -> {
  Integer time1 = Integer.valueOf(player1[1]);
  Integer time2 = Integer.valueOf(player2[1]);
  return time1.compareTo(time2);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, i wanted exactly this!
7

This is the easy way of Sorting String Array:
Arrays.sort(mystringarray);

Comments

3

Use

java.util.Arrays.sort(yourArray, new Comparator<String>() {
        @Override
        public int compare(String object1, String object2) {
            return Integer.valueOf(object1).compareTo(Integer.valueOf(object2));
        }
    });

Comparator will compare your strings as integers.

1 Comment

The answer is convert to numbers to sort as numbers - If not you are sorting in lexical order if you keep them as strings +1
2
ArrayList<String> names= new ArrayList<String>();
    names.add("sathish");
    names.add("Ravi");
    names.add("Praksh");
    names.add("pavithara");
    names.add("Duraga");
    names.add("uma");
    names.add("Upendar");
    System.out.println("Before sorting");
    System.out.println("Names : "+names);
    Collections.sort(names, new Comparator<String>() {

        @Override
        public int compare(String lhs, String rhs) {
            return lhs.compareToIgnoreCase(rhs);//Ascending order.
            //return (lhs.compareToIgnoreCase(rhs)*(-1));//Descending order.

        }
    });
    System.out.println("After sorting");
    System.out.println("Names : "+names);

output: Before sorting

Names : [sathish, Ravi, Praksh, pavithara, Duraga, uma, Upendar]

After sorting

Names : [Duraga, pavithara, Praksh, Ravi, sathish, uma, Upendar]

Comments

0

If possible use better data structure for your problem, use HashMap, with name to score mapping and , sort the hashmap with values.
If you want to go with arraylist as described by you, before sorting, convert them into integer and sort, then back to string.

Comments

0

You would probably be better off storing the names + results in objects, then storing those in an ArrayList. You can then sort very easily using a custom comparator, see the link for a simple example: http://www.javabeat.net/tips/20-sorting-custom-types-in-java.html

Comments

0

Score should be a class like

public class HighScore Comparable<HighScore>
{
    private String name;
    private int score;

    public Score( String name, int score )
    {
         this.name = name; 
         this.score = score;
    }//cons

    //getters
    public String getName() { 
         return name;
    }//met

    public int getScore() { 
         return score;
    }//met

    @Override
    public int compareTo( HighScrore b )
    {
          int diffScore = score - b.score;
          if( diffScore != 0)
              return diffScore;
          else
              return name.compareTo( b.name );
    }//met

    public boolean equals( Object o )
    {
         if( !(o instanceof HighScore))   
             return false;
         HighScore b = (HighScore) o;
         return score == b.score && name.equals( b.name );
    }//met
}//class

Then you can build score objects,

String[] stringParts[];
List<HighScore> listHighScore = new ArrayList<HighScore>();
for (int i=0; i<array1.size(); i++)
{
    stringParts =  array1.get(i).split(':'); 
    listHighScore.add( new HighScore( stringParts[ 0 ], Integer.parseInt( stringParts[ 1 ])) );

}//for

put them in a List and sort them through

Collections.sort( list );

Regards, Stéphane

Comments

0

You can use ArrayList instead of Array.

Please check this link

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.