Knowledge Walls
Java Master
Hyderabad, Andhra Pradesh, India
What are all the ways sort the list of String in Java
1078 Views
Example
import java.util.Arrays;
import java.util.Collections;

class MyObject {
    public static void main(String args[]) {

        String iArr[] = { "ca", "Ac", "aC" };
        Arrays.sort(iArr);
        for (String number : iArr) {
            System.out.println("ASC = " + number);
        }
        Arrays.sort(iArr, Collections.reverseOrder());

        for (String number : iArr) {
            System.out.println("DESC = " + number);
        }

    }
}
Output 
ASC = Ac
ASC = aC
ASC = ca
DESC = ca
DESC = aC
DESC = Ac
SortingUsingComparator
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortingUsingComparator {
    public static void main(String[] args) {
        List<String> names = new ArrayList<String>();
            names.add("Kumar");
            names.add("Dennis");
            names.add("John");
            names.add("Ravi");
            names.add("Zen");
            
        System.out.println("Before sorting...");
        System.out.println(names);
            
        Collections.sort(names, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                if (o1.compareTo(o2) > 0) {
                    return 1;
                }
                else {
                    return 0;
                }
            }
            
        });
        
        System.out.println("After sorting...");
        System.out.println(names);
    }
}
Output 
Before sorting...
[Kumar, Dennis, John, Ravi, Zen]

After sorting...
[Dennis, John, Kumar, Ravi, Zen]
Next Topics
Next lessons of current book.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details