erdomester
erdomester

Reputation: 11839

Android sort array

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?

Upvotes: 9

Views: 37877

Answers (8)

Kiril Kirilov
Kiril Kirilov

Reputation: 11257

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);
});

Upvotes: 19

challa sathish kumar
challa sathish kumar

Reputation: 366

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]

Upvotes: 2

Mayura
Mayura

Reputation: 91

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

Upvotes: 7

Nikhil
Nikhil

Reputation: 16194

You can use ArrayList instead of Array.

Please check this link

Upvotes: 0

Snicolas
Snicolas

Reputation: 38168

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

Upvotes: 0

Alex Orlov
Alex Orlov

Reputation: 18107

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.

Upvotes: 3

t_barbz
t_barbz

Reputation: 767

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

Upvotes: 0

sat
sat

Reputation: 41106

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.

Upvotes: 0

Related Questions