1

I need to sort an array of String like the following, in ascending order.

String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};

How to do that? I need help.

Rupak
  • 3,674
  • 15
  • 23
BB_Dev
  • 461
  • 1
  • 5
  • 11
  • 2
    did you try using [net.rim.device.api.util.Arrays.sort(Object[] a, Comparator c)](http://www.blackberry.com/developers/docs/3.7api/net/rim/device/api/util/Arrays.html#sort(java.lang.Object[], net.rim.device.api.util.Comparator)) ? – Tariq M Nasim May 29 '12 at 13:19

3 Answers3

5

This answer is based on Signare and HeartBeat's suggestion. Explore this link for details. Also this link, Sorting using java.util.Array might be helpful.

// Initialization of String array 
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};

// implementation of Comparator
Comparator strComparator = new Comparator() {
    public int compare(Object o1, Object o2) {
        return o1.toString().compareTo(o2.toString());
    }
};

// Sort
Arrays.sort(strs, strComparator);
Community
  • 1
  • 1
Rupak
  • 3,674
  • 15
  • 23
0

Try this -

import java.util.*;
import java.io.*;

public class TestSort1 {

String [] words = { "Réal", "Real", "Raoul", "Rico" };

 public static void main(String args[]) throws Exception {
    try {
  Writer w = getWriter();
  w.write("Before :\n");

  for (String s : words) {
    w.write(s + " ");
  }

  java.util.Arrays.sort(words);

  w.write("\nAfter :\n");
  for (String s : words) {
    w.write(s + " ");
  }
  w.flush();
  w.close();
}
catch(Exception e){
  e.printStackTrace();
}

 }

// useful to output accentued characters to the console
  public static Writer getWriter() throws UnsupportedEncodingException {
    if (System.console() == null) {
      Writer w =
        new BufferedWriter
         (new OutputStreamWriter(System.out, "Cp850"));
      return w;
    }
    else {
      return System.console().writer();
    }
  }
}
Rince Thomas
  • 4,158
  • 5
  • 25
  • 44
  • can i use "java.util.Arrays.sort(words)" in blackberry? – BB_Dev May 29 '12 at 13:01
  • Here are the [package javadocs for java.util][1] from the Blackberry JDE site. There is no Arrays class http://www.blackberry.com/developers/docs/6.0.0api/java/util/package-frame.html – BB_Dev May 29 '12 at 13:14
  • http://www.blackberry.com/developers/docs/3.7api/net/rim/device/api/util/Arrays.html#sort(java.lang.Object[] – Rince Thomas May 29 '12 at 13:45
0

Here is my solution:-

String str[]={"ASE","LSM","BSE","LKCSE","DFM"};

for(int j = 0; j < str.length; j++){
               for(int i = j + 1; i < str.length; i++) {
                   if(str[i].compareTo(str[j]) < 0) {
                       String t = str[j];
                       str[j] = str[i];
                       str[i] = t;
                   }
               }

    }
BB_Dev
  • 461
  • 1
  • 5
  • 11