【问题标题】:Storing string into hashmap [closed]将字符串存储到哈希图中[关闭]
【发布时间】:2014-03-11 16:42:00
【问题描述】:

我有一个返回某种字符串的方法。我想将单个单词及其出现次数存储在一个HashMap中?

例如,我有一个字符串-“今天是晴天,今天不会下雨”。现在我的 hashmap 应该是这样的

{Its:2, a:1, Sunny:1, day:1, today:2, not:1, going:1, rain:1}

我应该如何进行?

PS:我知道如何使用 HashMaps。在这种情况下,我的问题是我不知道如何解析给定的字符串并将单词及其出现次数存储起来。

【问题讨论】:

  • 您可以将字符串用作键,但您必须将数字存储为 Integer 对象,而不是 int 值。 “自动装箱”可能会处理这些数字,但最好明确说明。
  • 您可以查看 Google 的 Guava 中的 Multiset。它基本上是专门针对这种情况的地图。

标签: java string hashmap


【解决方案1】:

试试这样的:

String text = "Its a sunny day today Its not gonna rain today";
Map<String,Integer> map = new HashMap<String, Integer>();
for( String word : text.split(" ")) {
    Integer i = map.get(word);
    if( i == null ) {
        map.put(word, 1);
    } else {
        map.put(word, i+1);
    }
}

【讨论】:

  • +1 这是标准方法。
【解决方案2】:

这是一种使用匿名类来处理值初始化的变体:

// customized version of Map that doesn't return null from get()
Map<String, Integer> map = new HashMap<String, Integer>() {
    @Override
    public Integer get(Object key) {
        return containsKey(key) ? super.get(key) : 0;
    }
};
String s = "Its a sunny day today Its not gonna rain today";
for (String word : s.split(" "))
    map.put(word, map.get(word) + 1); // use is simple

输出:

{not=1, Its=2, sunny=1, a=1, today=2, day=1, rain=1, gonna=1}

它的行数与标准方法大致相同,但通过将处理单词首次出现的逻辑推送到地图中,使其更容易使用。

您可能希望将输入的大小写更改为全部小写,以便“Its”和“its”是“相同”的单词。

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    相关资源
    最近更新 更多