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(;

      while (true)


      String token =;

      if (".".equals(token))


      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 can i do it?
pls help me.
its urgent.

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.

//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>();

Map<String,Integer> m = new HashMap<String,Integer>();
for(String a : l) {
    m.put(a,(m.get(a)==null ? 1: m.get(a)+1 ));
//OR use the following code
Set<String> unique = new HashSet<String>(l);
for (String key : unique) {
    System.out.println(key + ": " + Collections.frequency(l, key));
commented: no explanation ... reviving a dead thread .. not even bothering to say whether it's an answer or a question, take your pick -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.