Java program to remove duplicates elements from a List

JavaObject Oriented ProgrammingProgramming

To remove duplicates from a List, the code is as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] args){
      ArrayList<String> list = new ArrayList<String>();
      list.add("Jacob");
      list.add("Gary");
      list.add("Gary");
      list.add("Harry");
      list.add("Harry");
      list.add("Kevin");
      System.out.println("List = "+list);
      Set<String> set = new LinkedHashSet<String>(list);
      System.out.println("List after removing duplicate elements = "+set);
   }
}

Output

List = [Jacob, Gary, Gary, Harry, Harry, Kevin]
List after removing duplicate elements = [Jacob, Gary, Harry, Kevin]

Example

Let us now see another example −

 Live Demo

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
   public static void main(String[] args){
      List<String> list = new ArrayList<String> (Arrays.asList("Ryan","Kevin","Ryan","Harry","Mark","Mark"));
      System.out.println("ArrayList = "+list);
      List<String> list2 = list.stream()
      .distinct()
      .collect(Collectors.toList());
      System.out.println("Updated ArrayList without duplicates = "+list2);
   }
}

Output

ArrayList = [Ryan, Kevin, Ryan, Harry, Mark, Mark]
Updated ArrayList without duplicates = [Ryan, Kevin, Harry, Mark]
raja
Published on 02-Jan-2020 10:44:15
Advertisements