Thursday, May 5, 2022

Question 8: Java coding interview questions

 Answer:

You can simply use stream and then collect it to set using Collections.toSet() method.
import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class RemoveDuplicatesFromListMain { public static void main(String[] args) { Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2}; List<Integer> listWithDuplicates = Arrays.asList(arr); Set<Integer> setWithoutDups = listWithDuplicates.stream().collect(Collectors.toSet()); setWithoutDups.forEach((i)->System.out.print(" "+i)); } }

You can use distinct as well to avoid duplicates as following.
change main method of above program as below.

Integer[] arr=new Integer[]{1,2,3,4,3,2,4,2}; List<Integer> listWithDuplicates = Arrays.asList(arr); List<Integer> listWithoutDups = listWithDuplicates.stream().distinct().collect(Collectors.toList()); listWithoutDups.forEach((i)->System.out.print(" "+i));

Don't miss the next article! 
Be the first to be notified when a new article or Kubernetes experiment is published.                            

   Share This

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS