-2

I have a list of user inputted names like this

String [] names = new String[x];

Then let's say they entered these names

names = {John, Bill, Sam, John, Joe, Bill};

How do I check for duplicates in this array? and then how do I print out what names are duplicates??

I have this so far, but it is not working

boolean duplicatenames = false;
for (int i = 0; i < names.length; i++) {

    for (int j = 0; j < names.length -1; j++) {

        if (names[i].equals(names[j])) {
            duplicatenames = true;
        }
    }
}

I think its just checking if there is a duplicate. but how I do I make it print out which names are duplicates?

For example:

"There are duplicate names. These names are: John, Bill"

1

5 Answers 5

2

You could iterate over the array, save the values to a map of frequencies, and then filter out only the keys that have more than a single occurrence. Java 8's streaming API allows for quite an elegant syntax to do so:

List<String> duplicates = 
        Arrays.stream(names)
                .collect(Collectors.groupingBy(Function.identity(), 
                                               Collectors.counting()))
                .entrySet()
                .stream()
                .filter(e -> e.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

1 Comment

I've heard OP's gasps and sighs even at my place.
0

Hint:

  1. loop over the array and find the match. If found add that entry in a list.
  2. Iterate over the list of duplicate element and print it.

3 Comments

Could you please show me an example? I understand the logic, but I just don't know how to put it into code. I just started a few weeks ago..
As so often: should multiple (3-fold, 4-fold,...n-fold) occurrences result in 2 or 3 or n-1 duplicates being reported? If not, is this algorithm correct? If not, how can it be fixed? - In the light of this, given arbitrary inputs (e.g. a zillion times "John"), is there a better algorithm?
@laune yes there are so many better algorithm. Soora has already provided a link. I guess I am a bit late to see this. I hope you got your answer.
0

Build a Map of name to counter. In order to have an updatable counter, use AtomicInteger. Then print all map entries with a counter >= 2. If you use a LinkedHashMap, then values will be listed in the original order of first seen.

String[] names = {"John", "Bill", "Sam", "John", "Joe", "Bill", "John"};

Map<String, AtomicInteger> nameCount = new LinkedHashMap<>(names.length * 4 / 3 + 1);
for (String name : names) {
    AtomicInteger count = nameCount.get(name);
    if (count == null)
        nameCount.put(name, new AtomicInteger(1));
    else
        count.incrementAndGet();
}
StringBuilder buf = new StringBuilder();
for (Entry<String, AtomicInteger> entry : nameCount.entrySet()) {
    String name = entry.getKey();
    int count = entry.getValue().get();
    if (count > 1) {
        if (buf.length() == 0)
            buf.append("There are duplicate names. These names are: ");
        else
            buf.append(", ");
        buf.append(name);
        if (count > 2)
            buf.append(" (").append(count).append(" times)");
    }
}
if (buf.length() != 0)
    System.out.println(buf);
else
    System.out.println("There are no duplicate names.");

Output

There are duplicate names. These names are: John (3 times), Bill

Comments

0
String[] names = {"John","Doe","John","Doe","Hello"};

Set<String> duplicatesNames = new HashSet<String>();
Set<String> testSet = new HashSet<String>();
for(String name : names){
    boolean check = testSet.add(name);
    if(!check){
        duplicatesNames.add(name);
    }
}
System.out.println("Duplicates names are " + duplicatesNames);

Comments

0

Use a Set to save duplicate names as they occur. Print them as you wish.

Set<String> duplicateNameSet = new HashSet<String>();

for (int i = 0; i < names.length; i++)
   for (int j = 0; j < names.length -1; j++) {
      if (names[i].equals(names[j])) {
         duplicateNameSet.add(names[j])    
   }
if(duplicateNameSet.isEmpty())
    System.out.println( "There are duplicate names.");
else
    System.out.println( "There are duplicate names. These names are: "+duplicateNameSet);

6 Comments

There's no need to maintain duplicateNames - the information is readily available from Set. And it should be used to control this println.
@laune: So, you are saying, duplicate names should be printed as they occur?
I was saying that there is no need for the variable duplicateNames, even when you want to suppress the final println when there are no duplicates.
Oh okay, got it. You are right, thanks. I will refactor my code.
You may want to count the number of { and } ... since they are not equal.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.