How to remove duplicates from an ArrayList in Java?

Java 8Object Oriented ProgrammingProgramming

In Java, Set object does not allow duplicate elements so you can remove duplicates from a list by creating a set object by passing required List object to its constructor.

Example:

import java.util.ArrayList;
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);
      System.out.println(set);
   }
}

Output:

[JavaFx, Java, WebGL, OpenCV]
raja
Published on 17-Jan-2018 05:59:24
Advertisements