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 arrayList.stream() 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;
import java.util.stream.Collectors;
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(s[j]);
}
}
}
System.out.println("from stream and filter method :-");
Set h = new HashSet();
Arrays.asList(s).stream().filter(r -> !h.add(r)).collect(Collectors.toList()).forEach(System.out::println);
}
}
Output :-
duplicate String from for loop is :-
dell
hp
from stream and filter method :-
dell
hp