Wednesday 5 July 2017

How to sort ArrayList in JAVA

CollectionSort.java

package java8s;

import java.util.*;

public class CollectionSort {

          public static void main(String... args)
          {

                       List l = new ArrayList();

                       l.add("Bhubaneswar");
                       l.add("Cuttack");
                       l.add("Paradeep");
                       l.add("Jagatsinghpur");
                       l.add("Kujanga");

                       Collections.sort(l);

                            
                       System.out.println("Location : "+l);
                            
          }
}
Output

Location : [Bhubaneswar, Cuttack, Jagatsinghpur, Kujanga, Paradeep]

How to avoid duplicate values from JAVA List / ArrayList

Hiii frnds, this is a nice question in interview forum, so let's see how to remove duplicate objects from List / ArrayList

ArrayListExample.java

package java8s;

import java.util.*;
public class ArrayListExample {

     public static void main(String[] args) {
          ArrayList al=new ArrayList();
          al.add("first");
          al.add("second");
          al.add("third");
          al.add("first");
          al.add("first");
         
          ArrayList al1=new ArrayList(new LinkedHashSet(al));
         
          Iterator it=al1.iterator();
          while(it.hasNext())
          {
              System.out.println(it.next());
          }

     }

}

Output

first
second
third