【问题标题】:print only repeated words in java在java中只打印重复的单词
【发布时间】:2015-07-24 04:55:37
【问题描述】:

我只想显示在一个字符串中出现多次的单词,不应该打印单个出现的字符串。我还想打印长度大于 2 的字符串(以消除 is,was,the 等)..

我尝试的代码..打印所有字符串并显示是出现次数..

代码:

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


}

输出:

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

不应打印单一外观的字符串... 我也想打印长度大于 2 的字符串(以消除 is,was,the 等)..

【问题讨论】:

  • TreeMap的toString方法是这样设计的。最好编写自己的方法来打印 TreeMap。

标签: java arrays string treemap


【解决方案1】:

使用它

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

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

【讨论】:

    【解决方案2】:

    跟踪地图中出现的次数将允许您执行此操作。

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

    【讨论】:

    • 输出为:palace=2, world=3
    【解决方案3】:

    要仅获取出现多次的单词,您必须过滤地图。

    根据您的 Java 版本,您可以使用以下任一方式:

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

    或者从 Java 8 开始这个等价的 Lambda 表达式:

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

    关于漂亮的打印,您必须在迭代结果时做类似的事情。

    【讨论】:

      【解决方案4】:

      使用下面的代码

      for (String key : wordcheck.keySet()) {
      
          if(wordcheck.get(key)>1)
              System.out.println(key + " " + wordcheck.get(key));
      

      }

      【讨论】:

        【解决方案5】:
        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);
        
        
        }
        

        【讨论】:

        • 输出为:-重复字大小:3 重复字:[of, Palace, world]
        【解决方案6】:

        TreeMap.toString() 继承自 AbstractMap 并且文档指出

        返回此地图的字符串表示形式。字符串表示由一个键值映射列表组成,按映射的 entrySet 视图的迭代器返回的顺序,括在大括号(“{}”)中。相邻映射由字符“、”(逗号和空格)分隔。每个键值映射都呈现为键,后跟等号(“=”),后跟关联的值。键和值通过 String.valueOf(Object) 转换为字符串。

        所以最好编写自己的方法,以您想要的方式打印出 TreeMap。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-29
          • 1970-01-01
          相关资源
          最近更新 更多