5

我的任务即将结束,我被指示要做的最后一件事是:

  • 使用 keySet() 检索键集(映射的字符串部分)。循环这个集合并打印出单词及其计数。

我已经使用 keySet() 方法打印出 HashMap 中的键数,但我还没有做的是找到 HashMap 中每个单词的长度,然后打印出每个单词中的字符数。我目前不确定我应该如何做到这一点。我假设我会使用一些时间的 for 循环来遍历我已经完成的 keySet(),然后使用类似 .length() 的方法来找出每个单词的长度,然后以某种方式打印出来?

到目前为止,这是我的相关代码:

主班

package QuestionEditor;
import java.util.Set;
public class Main{
    public static void main (String[] args) {
        WordGroup secondWordGroup = new WordGroup ("When-you-play-play-hard-when-you-work-dont-play-at-all");


         Set<String> set = secondWordGroup.getWordCountsMap().keySet();

         System.out.println("set : " + set + "\n");

         for(String key : set)
         {
             System.out.println(key);
         }
        }
    }

WodGroup 类

package QuestionEditor;
import java.util.HashMap;

public class WordGroup {

    String  word;

    // Creates constructor which stores a string value in variable "word" and converts this into lower case using
    // the lower case method.
    public WordGroup(String aString) {

        this.word = aString.toLowerCase();
    }

    public String[] getWordArray() {

        String[] wordArray = word.split("-");
        return wordArray;
    }

    public HashMap<String, Integer> getWordCountsMap() {

        HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();

        for (String word : this.getWordArray()) {
            if (myHashMap.keySet().contains(word)) {
                myHashMap.put(word, myHashMap.get(word) + 1);
            } else {
                myHashMap.put(word, 1);
            }

        }

        return myHashMap;
    }   
}

任何有关如何做到这一点的帮助将不胜感激,谢谢。

更新 所以当我的代码编译时,我得到了输出:

Key: play has 3 counter
Key: all has 1 counter
Key: at has 1 counter
Key: work has 1 counter
Key: hard has 1 counter
Key: when has 2 counter
Key: you has 2 counter
Key: dont has 1 counter

但我真正想做的是打印出每个单词中的字符数量。因此,例如,play 将计算 4 次,all 将计算 3 次,at 将计算 2 次等。关于如何实现这一点的任何想法?

4

2 回答 2

3

您可能缺少的部分是:您可以使用然后访问您的地图值,如下所示:

Map<String, Integer> whateverMap = ... coming from somewhere

for (String key : whateverMap.keySet()) {
  Integer countFromMap = whateverMap.get(key);
  System.out.println("Key: " + key + " has " + countFromMap + " counter");

上面的内容是让你继续前进的例子,我没有通过编译器运行它。

我的观点是:有多种方法可以迭代您存储在 Map 中的元素。您可以使用entrySet()来检索Entry对象;或者您迭代键,并使用每个键查找值。

于 2016-11-12T20:28:01.860 回答
2

您可以使用 Java 8 中的流 API 创建一个Map<String,Integer>

Map<String, Integer> stringIntegerMap = set.stream().collect(HashMap::new,
    (hashMap, s) -> hashMap.put(s, s.length()), HashMap::putAll);

stringIntegerMap.forEach((key,value) ->System.out.println(key + " has length: "+key.length() + " and count: "+value));

collect 函数的第二个参数是一个累加器。您正在从键集中累积字符串的 hasmap 及其长度

于 2016-11-12T20:38:48.717 回答