How to sort an ArrayList in Java in ascending order?

Java 8Object Oriented ProgrammingProgramming

You can sort an ArrayList using the sort() method of the Collections class this method accepts a list object as a parameter and sorts the contents of it in ascending order.

Example:

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;

public class ArrayListSample {
   public static void main(String[] args) {
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFx");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      Set<String> set = new LinkedHashSet<String>(list);
      Collections.sort(list);
      System.out.println(list);
   }
}

Output:

[Java, JavaFx, OpenCV, WebGL]
raja
Published on 17-Jan-2018 10:37:58
Advertisements