I’ve created an arraylist like this
ArrayList<String> entries = new ArrayList<String>();
entries.add("0 - name1");
entries.add("1000 - name2");
entries.add("1004 - name4");
entries.add("1002 - name3");
entries.add("10000 - name5");
entries.add("2000 - name5");
The list always starts with a number between 0 and 15,000 so when i sort i would like it to just sort based on the number none of the numbers will ever match and they should be assorted in an ascending order.
How can this be done with java can i use a comparator?
yes, you can 🙂
with syntax :
Collections.sort(entries,comparator);– you need to import java.util.Collections and write comparator that makes what you want. You may as well try.sort(entries)using default comparator (but here it will not work 🙂 ).here’s complete solution:
Also – I strongly suggest to declare lists likes this:
List<String> entries = new ArrayList<String>();Later you may find benefits of usingLinkedListin place ofArrayList– then changing implementation of used list would be simplest possible.Plz google “Program to interface not to implementation”. 🙂