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?

2

3 Answers 3

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]);
    }
});
Sign up to request clarification or add additional context in comments.

3 Comments

thx before, but how if an array is dynamic with loop
Your array changed at sorting time?
This is off topic on this post, but this will depends on your "dynamic array".
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

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.