0

Hello i have some simple code like this

  String[] myString1= {"Hidayat", "20"};
  outerArr.add(myString1);

  String[] myString2= {"Ryan", "10"};
  outerArr.add(myString2);

  String[] myString2= {"irwan", "5"};
  outerArr.add(myString2);

anyone know how to sort array outerArr with ascending by number?

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31

3 Answers3

1

You can use Comparator interface for custom sorting:

Collections.sort(outerArr, new Comparator<String[]>() {
    public int compare(String[] o1, String[] o2)
    {
        // for example you can compare integers
        return Integer.parseInt(o2[1]) - Integer.parseInt(o1[1]);
    }
});
Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60
0

For that case i prefer TreeMap.The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.

TreeMap<String, String> map = new TreeMap<>();
map.put("20", "Hidayat");
map.put("10", "Ryan");
map.put("5", "irwan");

For retrieving the values

map.get("10"); // output = Ryan
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
  • You should add that this has some cost on each insertion, suppression of course so this depends on the usage. For a pretty static map, this is not a problem, for a list that will be update a lot but only need to be sorted (printed or used) once in a while, I would stay with a list – AxelH Jan 12 '17 at 10:52
0

Another way to do this if you are using Java 8 is using Lambda, first create a class contain 2 member fields for the string and the number with getter for each member and then called this way :

outerArr.sort((Person o1, Person o2)->o1.getAge()-o2.getAge());

If you don't want to create a new class you can call :

outerArr.sort((String[] o1, String[] o2)->Integer.parseInt(o1[1])-Integer.parseInt(o2[1]));
Abdennacer Lachiheb
  • 4,388
  • 7
  • 30
  • 61