Java 8 streams to find the duplicate elements?

There are multiple way in Java 8 streams to find the duplicate elements.

From filter() and HashSet() method :-

  • Create HashSet object of Integer type.
  • First convert Arrays to list using Arrays.asList method
  • Now get the Stream data from List using arrayList.stream() method.
  • After Streaming,inside filter are add duplicate elements.
  • From Collectors.toSet() method we are collect all duplicate elements.
  • Print the numbers from forEach() method.

From frequency and filter method :-

  • First convert Arrays to list using Arrays.asList method
  • Now get the Stream data from List using arrayList.stream() method.
  • Inside filter method collections.frequency() method find the frequency of element present in the list.
  • If frequency is greater than one means there are multiple duplicate elements.
  • From Collectors.toSet() method we are collect all duplicate elements.
  • Print the numbers from forEach() method.

          Syntax :-  public static int frequency(Collection<?> c, Object o)

				
					import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FindDuplicateElements {
	public static void main(String[] args) {
		// from filter and hashset method
		List<Integer> listOne = Arrays.asList(18, 90, 22, 80, 98, 23, 87, 20, 80, 18, 22, 65, 21, 80);
		Set<Integer> hs = new HashSet<Integer>();
		System.out.println("from filter and hashset method :- ");
		listOne.stream().filter(r -> !hs.add(r)).collect(Collectors.toSet()).forEach(System.out::println);

		// from frequency and filter method
		System.out.println("from frequency and filter method :- ");
		List<Integer> listTwo = Arrays.asList(18, 90, 22, 80, 98, 23, 87, 20, 80, 18, 22, 65, 21);
		listTwo.stream().filter(e -> Collections.frequency(listTwo, e) > 1).collect(Collectors.toSet())
				.forEach(System.out::println);
	}
}

				
			

Output :-
from filter and hashset method :-
80
18
22
from frequency and filter method :-
80
18
22