how to find dulicates in java code example
Example 1: java find duplicates in array
package dto;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DuplicatesInArray{
public static void main(String args[]) {
String[] names = { "Java", "JavaScript", "Python", "C", "Ruby", "Java" };
System.out.println("Finding duplicate elements in array using brute force method");
for (int i = 0; i < names.length; i++) {
for (int j = i + 1; j < names.length; j++) {
if (names[i].equals(names[j]) ) {
}
}
}
System.out.println("Duplicate elements from array using HashSet data structure");
Set<String> store = new HashSet<>();
for (String name : names) {
if (store.add(name) == false) {
System.out.println("found a duplicate element in array : "
+ name);
}
}
System.out.println("Duplicate elements from array using hash table");
Map<String, Integer> nameAndCount = new HashMap<>();
for (String name : names) {
Integer count = nameAndCount.get(name);
if (count == null) {
nameAndCount.put(name, 1);
} else {
nameAndCount.put(name, ++count);
}
}
Set<Entry<String, Integer>> entrySet = nameAndCount.entrySet();
for (Entry<String, Integer> entry : entrySet) {
if (entry.getValue() > 1) {
System.out.println("Duplicate element from array : "
+ entry.getKey());
}
}
}
}
Output :
Finding duplicate elements in array using brute force method
Duplicate elements from array using HashSet data structure
found a duplicate element in array : Java
Duplicate elements from array using hash table
Duplicate element from array : Java
Example 2: find-array-duplicates
npm i find-array-duplicates
import duplicates from 'find-array-duplicates'
const names = [
{ 'age': 36, 'name': 'Bob' },
{ 'age': 40, 'name': 'Harry' },
{ 'age': 1, 'name': 'Bob' }
]
duplicates(names, 'name').single()