An array list contains some data that needs to be sorted.
Data:
A1
A5
B1
A7
B3
After sort I need to be shown like below
A1
A5
A7
B1
B3
Please help on this.
An array list contains some data that needs to be sorted.
Data:
A1
A5
B1
A7
B3
After sort I need to be shown like below
A1
A5
A7
B1
B3
Please help on this.
List<String> list = new ArrayList<String>();
list.add("A1");
list.add("A5");
list.add("B1");
list.add("A7");
list.add("B3");
Collections.sort(list);//For ascending order
Collections.reverse(list);//For descending order
Also if you want to sort any custom object then check below link for implementation of comparable/comparator: http://www.journaldev.com/780/comparable-and-comparator-in-java-example
If your data is just String data, then you can simply use the following piece of code:
List<String> data = Arrays.asList("A1", "A5", "B1", "A7", "B3");
Collections.sort(data);
Otherwise, you will need to write a custom logic to sort it.
Refer to this documentation:
You can use custom comparator like this:-
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
});