find duplicate elements in array in java?

There are multiple way to find duplicate elements in array in java.

Using nested for loop :-

  • First we create nested for loop and iterate the elements.
  • Now from if condition we check first elements is equals to next elements.
  • If elements is equals, then print data s[j].

Using stream() method :-

  • First convert String Arrays to list using Arrays.asList method
  • Now get the Stream data from List using method
  • Create String type hashset object.
  • By filter we add duplicate data from hashset.
  • Now collect data into list and print from forEach method.
					import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class DuplicateArrayElements {
	public static void main(String[] args) {
		String[] s = { "dell", "hp", "sony", "dell", "ibm", "hp", "microsoft" };

		System.out.println("duplicate String from for loop is :- ");
		for (int i = 0; i < s.length - 1; i++) {
			for (int j = i + 1; j < s.length; j++) {
				if ((s[i].equals(s[j])) && (i != j)) {

		System.out.println("from stream and filter method :-");
		Set<String> h = new HashSet<String>();
		Arrays.asList(s).stream().filter(r -> !h.add(r)).collect(Collectors.toList()).forEach(System.out::println);


Output :-
duplicate String from for loop is :-
from stream and filter method :-