Question
Write a program in java that will be able to print out the duplicates of names.
Answers
GPT 3.5
Sure! Here's a Java program that prints out the duplicates of names in an array:
```java
import java.util.HashMap;
import java.util.Map;
public class DuplicateNames {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Alice", "Charlie", "David", "Bob"};
Map<String, Integer> nameCount = new HashMap<>();
for (String name : names) {
if (nameCount.containsKey(name)) {
nameCount.put(name, nameCount.get(name) + 1);
} else {
nameCount.put(name, 1);
}
}
System.out.println("Duplicate names:");
for (Map.Entry<String, Integer> entry : nameCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
}
}
}
}
```
This program creates a HashMap to store the count of each name in the input array. It then iterates through the names array and updates the count in the HashMap for each name. Finally, it prints out the names that have a count greater than 1, indicating duplicates.
```java
import java.util.HashMap;
import java.util.Map;
public class DuplicateNames {
public static void main(String[] args) {
String[] names = {"Alice", "Bob", "Alice", "Charlie", "David", "Bob"};
Map<String, Integer> nameCount = new HashMap<>();
for (String name : names) {
if (nameCount.containsKey(name)) {
nameCount.put(name, nameCount.get(name) + 1);
} else {
nameCount.put(name, 1);
}
}
System.out.println("Duplicate names:");
for (Map.Entry<String, Integer> entry : nameCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey());
}
}
}
}
```
This program creates a HashMap to store the count of each name in the input array. It then iterates through the names array and updates the count in the HashMap for each name. Finally, it prints out the names that have a count greater than 1, indicating duplicates.
Related Questions
Write a java program to read the names and ages of 10 people and print the name of the oldest person
Write a program in java that will be able to print out the duplicates of names.public class duplicat...
Write a program in java that will be able to print out the duplicates of names.
Public class duplic...