1

I want to sort an ArrayList of type String using a comparator. I have only found examples on how to do it if an ArrayList stores objects.

I have an ArrayList of strings that have 10 symbols and last 5 of those symbols are digits that form a number. I want to solve an array list in ascending order of those numbers that are at the end of each string. How can I do that?

Thanks!

  • 3
    `String` **is** an `Object`. What have you tried (exactly)? Let's see some code. – Elliott Frisch Oct 28 '17 at 16:31
  • `private static ArrayList allCodes = new ArrayList(); //add some codes in .... private void sortAllCodesNumbers (){ Collections.sort(allCodes, allCodes.getCompByNum()); } ` – Mouthful OfTech Oct 28 '17 at 16:39
  • `public static Comparator getCompByNum() { Comparator comp = new Comparator(){ @Override public int compare(allBooks b1, allBooks b2) { String IDnumbers1 = b1.substring(AUTHOR_ID_LENGHT+GENRE_LENGTH); int number1 = Integer.parseInt(IDnumbers1); String IDnumbers2 = b2.substring(AUTHOR_ID_LENGHT+GENRE_LENGTH); int number2 = Integer.parseInt(IDnumbers1); return number1.compareTo(number2); } }; return comp; }` – Mouthful OfTech Oct 28 '17 at 16:42
  • Variant of https://stackoverflow.com/questions/16425127/how-to-use-collections-sort-in-java-specific-situation ? – tevemadar Oct 28 '17 at 16:43
  • check this:List list= new ArrayList(); list.add("abc456"); list.add("abc123"); list.add("abc012"); System.out.println(list); Collections.sort(list); System.out.println(list); output:[abc456, abc123, abc012] [abc012, abc123, abc456] – ASR Oct 28 '17 at 16:51

3 Answers3

3

This is one way to accomplish your task; sorted accepts a Comparator object.

List<String> result = myArrayList.stream().sorted(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))))
                                          .collect(Collectors.toList());

or simply:

myArrayList.sort(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

Collections.sort can sort you a list with a Comparator. Plus you need String.substring:

Collections.sort(list, new Comparator<String>(){
    @Override
    public int compare(String o1, String o2) {
        return o1.substring(5).compareTo(o2.substring(5));
    }
});
tevemadar
  • 12,389
  • 3
  • 21
  • 49
0
Collections.sort(list, String::compareTo);

The above code does the job.

If you want more control, you could use/chain with one of the static methods available in the Comparator Interface.

Collectios.sort(list, Comparator.comparing(String::CompareTo).thenComparingInt(String::length));
Amos Kosgei
  • 877
  • 8
  • 14