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();
CodePudding user response:
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]