-12

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.

learner
  • 3,092
  • 2
  • 21
  • 33

4 Answers4

4
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

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Chinmay
  • 113
  • 7
0

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:

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

anacron
  • 6,443
  • 2
  • 26
  • 31
0

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);
    }
});
deepansh2323
  • 261
  • 1
  • 8
0

You can use sort method of java.util.Collections class. You can define your own Comparator. See more here.

Viet Tran
  • 1,173
  • 11
  • 16