JavaLearner
JavaLearner

Reputation: 322

print only repeated words in java

I want to display only the words that appear more than once in a string, single appearance of string should not be printed. Also i want to print strings whose length is more than 2 (to eliminate is,was,the etc)..

The code which I tried..prints all the strings and shows is occurrence number..

Code:

public static void main(String args[])
{
    Map<String, Integer> wordcheck = new TreeMap<String, Integer>();
    String string1="world world is new world of kingdom of palace of kings palace";
    String string2[]=string1.split(" ");


    for (int i=0; i<string2.length; i++) 

     {
        String string=string2[i];
        wordcheck.put(string,(wordcheck.get(string) == null?1:   (wordcheck.get(string)+1)));

      }

    System.out.println(wordcheck);


}

Output:

{is=1, kingdom=1, kings=1, new=1, of=3, palace=2, world=3}

single appearance of string should not be printed... also i want to print strings whose length is more than 2 (to eliminate is,was,the etc)..

Upvotes: 0

Views: 1116

Answers (6)

CR7
CR7

Reputation: 710

Use it

for (String key : wordcheck.keySet()) {

        if(wordcheck.get(key)>1)
            System.out.println(key + " " + wordcheck.get(key));
}

Upvotes: 2

Akhil Sudhakaran
Akhil Sudhakaran

Reputation: 357

Use the below code

for (String key : wordcheck.keySet()) {

    if(wordcheck.get(key)>1)
        System.out.println(key + " " + wordcheck.get(key));

}

Upvotes: 1

Naman Gala
Naman Gala

Reputation: 4692

TreeMap.toString() is inherited from AbstractMap and the documentation states that

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

So better you write your own method that prints out the TreeMap in a way you want.

Upvotes: 0

Carsten
Carsten

Reputation: 2147

To get only the words occurring more then once, you have to filter your map.

Depending on your Java version you can use either this:

List<String> wordsOccuringMultipleTimes = new LinkedList<String>();
for (Map.Entry<String, Integer> singleWord : wordcheck.entrySet()) {
    if (singleWord.getValue() > 1) {
        wordsOccuringMultipleTimes.add(singleWord.getKey());
    }
}

or starting with Java 8 this equivalent Lambda expression:

List<String> wordsOccuringMultipleTimes = wordcheck.entrySet().stream()
        .filter((entry) -> entry.getValue() > 1)
        .map((entry) -> entry.getKey())
        .collect(Collectors.toList());

Regarding the nice printing, you have to do something similar while iterating over your result.

Upvotes: 1

VirtualMichael
VirtualMichael

Reputation: 721

Keeping track of the number of occurrences in a map will allow you to do this.

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class Test1
{
    public static void main(String[] args)
    {
        String string1="world world is new world of kingdom of palace of kings palace";
        String string2[]=string1.split(" ");
        HashMap<String, Integer> uniques = new HashMap<String, Integer>();
        for (String word : string2)
        {
            // ignore words 2 or less characters long
            if (word.length() <= 2)
            {
                continue;
            }
            // add or update the word occurrence count
            Integer existingCount = uniques.get(word);
            uniques.put(word, (existingCount == null ? 1 : (existingCount + 1)));
        }

        Set<Entry<String, Integer>> uniqueSet = uniques.entrySet();
        boolean first = true;
        for (Entry<String, Integer> entry : uniqueSet)
        {
            if (entry.getValue() > 1)
            {
                System.out.print((first ? "" : ", ") + entry.getKey() + "=" + entry.getValue());
                first = false;
            }
        }

    }
}

Upvotes: 1

vikash
vikash

Reputation: 129

public static void main(String args[])
{
    Map<String, Integer> wordcheck = new TreeMap<String, Integer>();
    String string1="world world is new world of kingdom of palace of kings palace";
    String string2[]=string1.split(" ");
    HashSet<String> set = new HashSet<String>();

    for (int i=0; i<string2.length; i++) 

     {
        String data=string2[i];
       for(int j=0;j<string2.length;j++)
       {
           if(i != j)
           {
            if(data.equalsIgnoreCase(string2[j]))
            {

                set.add(data);

            }
           }
       }

      }

    System.out.println("Duplicate word size :"+set.size());
    System.out.println("Duplicate words :"+set);


}

Upvotes: 0

Related Questions