0

I want to sort a ArrayList of Strings (descending order) which are in the following format : "row,column".

But since I can't find a way to do that, I thought of converting the ArrayList of Strings into ArrayList<ArrayList> and sorting it in descending order.

For e.g.,

the strings : "21,10", "19,25", "32,5" will be converted into an ArrayList<ArrayList> like so: [[32,5],[21,10],[19,25]].

NOTE : I only want to sort in descending order based on the first index of inner ArrayList.

Zizou
  • 67
  • 5
  • 1
    In your question you have mentioned ArrayList, while in the description you mention Strings? – GunJack Jun 17 '22 at 03:16
  • What is the criteria for sorting? Are you sorting in descending order by first element or second element? – GunJack Jun 17 '22 at 03:17
  • 2
    Does this answer your question? [Sorting ArrayList by specific value](https://stackoverflow.com/questions/35905802/sorting-arraylist-by-specific-value) or better yet: [Sort ArrayList of custom Objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – sorifiend Jun 17 '22 at 03:18
  • @GunJack I have added clarifying statements of my original intention and then based on that why I'm trying to descending sort an ArrayList>. Please suggest if that is not clear. – Zizou Jun 17 '22 at 03:18
  • @sorifiend thanks for that link! I think this comment is perfect for my usecase : https://stackoverflow.com/a/35905950/9616025. Unfortunately I don't know enough of Java to understand how to modify that to my use case where I want to use the 0th index element as the comparator. Do you know how I could do that? – Zizou Jun 17 '22 at 03:22
  • 1
    Dies this answer your question? https://stackoverflow.com/questions/10794148/sort-an-arraylist-of-arraylist-of-integers – GunJack Jun 17 '22 at 03:24
  • @GunJack thanks for the link! How do I reverse this sort? I don't understand that part, I'm a java newbie. – Zizou Jun 17 '22 at 03:27
  • 1
    change `return o1.get(0).compareTo(o2.get(0));` to `return o2.get(0).compareTo(o1.get(0));` – GunJack Jun 17 '22 at 03:30

1 Answers1

2

This is how you can achieve it with an Arraylist of strings.

ArrayList<String> list = new ArrayList<String>();
list.add("21,10");
list.add("19,25");
list.add("32,5");

Once you have your list, you can simply use Collections.sort() method.

Collections.sort(list);

For reverse order simply add another argument to the sort method.

Collections.sort(list, Collections.reverseOrder());

Print the list to verify. System.out.println(list);

Here is a running code example.

https://onecompiler.com/java/3y7ahcm6x

GunJack
  • 1,928
  • 2
  • 22
  • 35