public class duplicate
   
  {

    public static void main(String[] args)throws IOException

      {

      System.out.println("Enter words separated by spaces ('.' to quit):");

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

      Scanner input = new Scanner(System.in);

      while (true)

      {

      String token = input.next();

      if (".".equals(token))

      break;

      if (!s.add(token))

      System.out.println("Duplicate detected: " + token);

      }

      System.out.println(s.size() + " distinct words:\n" + s);


   }
}

my program detects and prints the duplicate words.but i also need to print the number of duplicate words.how can i do it?
pls help me.
its urgent.

Edited 6 Years Ago by Nick Evan: added code-tags

A simple way use a Map of type <String,Integer>, so the Key is the String and the value is the number of times it occurs.
When you encounter a word, you can check for its occurrence by invoking in the containsKey() method on that map. If containsKey() returns false for that String it means you have encountered a new word, so add it to the Map and put and Integer value of '1' against it, on the other hand if containsKey() returns true, you have encountered a duplicate, so just acquire the Integer object mapped against that String in your Map and increment it by '1', so that way you are recording the number of times each word occurs.
Finally at the end of your input, your Map will contain all the unique words it encountered in the 'Key' and the number of times each of those words occurred in the corresponding 'Value' entry against that String.

Edited 6 Years Ago by stephen84s: n/a

//finding out duplicate elements in a list
import java.util.*;
public class RD {
public static void main(String arg[]) {

List<String> l  = new ArrayList<String>();
l.add("A");l.add("B");l.add("A");l.add("C");l.add("B");l.add("A");

Map<String,Integer> m = new HashMap<String,Integer>();
for(String a : l) {
    m.put(a,(m.get(a)==null ? 1: m.get(a)+1 ));
}
System.out.println(m);
//OR use the following code
Set<String> unique = new HashSet<String>(l);
for (String key : unique) {
    System.out.println(key + ": " + Collections.frequency(l, key));
}
}
}
Comments
no explanation ... reviving a dead thread .. not even bothering to say whether it's an answer or a question, take your pick
This article has been dead for over six months. Start a new discussion instead.