Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

find Duplicate Element from a List of Integer without using Stream's distinct method

Recently this question is asked in Interview :
How to find the Duplicate Elements from a List of Integer without using java Stream’s distinct method ?

This should be done by Java’s Stream API but should not use distinct() method.

for e.g List listOfInt = new ArrayList();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do this using frequency collectors. Have not looked at optimization , but this will not use distinct

import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import static java.util.stream.Collectors.toSet;
import java.util.Collections;

public class DetectDuplicates{
    public static void main(String args[]) {
      int x=10;
      int y=25;
      int z=x+y;
      List<Integer> companyIds = new ArrayList<Integer>();
      companyIds.add(1);
      companyIds.add(1);
      companyIds.add(2);
      companyIds.add(3);
      
      Set<Integer> duplicateCompanies = companyIds
                .stream()
                .filter(company -> Collections.frequency(companyIds, company) > 1)
                .collect(toSet());
      System.out.println("Duplicate companies " + duplicateCompanies);
    }
}

This will print

Duplicate companies [1, 3]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading