Map<String, Integer> 中的计数问题 [英] Problem counting in Map&lt;String, Integer&gt;

查看:29
本文介绍了Map<String, Integer> 中的计数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个关于计数的问题一个单词在 ArrayList 中的次数:

I asked a question about counting the number of times a word is in ArrayList:

ACU ACU ACU ACU ACY ACY AER AER AER AGC

所以
ACU 我们将得到 4,
ACY 我们会得到 2,
AER 我们将得到 3,
AGC 我们将得到 1.

So for
ACU we will get 4,
ACY we will get 2,
AER we will get 3,
AGC we will get 1.

我得到了一些帮助,但我无法让它发挥作用.
达伦给了我一个非常重要的答案:

I got some help but I cannot make it work.
Darren gave me a very important answer:

Map<String, Integer>wordCount = new HashMap<String, int>();
  for(String seq : yourWordList){
     wordCount.put(seq, wordCount.get(seq++));
  }

但是在wordCount.put(seq, wordCount.get(seq++));我收到无法从 String 转换为 int 的错误,我尝试修改代码以使其正常工作但我得到的数字不正确

But in the part wordCount.put(seq, wordCount.get(seq++)); I get an error that cannot convert from String to int, I tried to modify the code to work but I'm getting incorrect numbers

ACU 0ACU 1ACU 1ACU 1ACY 1ACY 22AER 3AER 3

ACU 0 ACU 1 ACU 1 ACU 1 ACY 1 ACY 2 AER 2 AER 3 AER 3

int value=0;
Map<String, Integer>wordCount = new HashMap<String, Integer>();
for(String seq : WordList){
  Set<String> set = wordCount.keySet();
  value = set.size();
  wordCount.put(seq, value));
}

请帮我解决这个问题.谢谢大家.

Please help me on this one. Thanks to all.

推荐答案

你想要的是:

Map<String, Integer>wordCount = new HashMap<String, Integer>();
for (String seq : yourWordList) {
  Integer count = wordCount.get(seq);
  wordCount.put(seq, count == null ? 1 : count + 1);
}

Map 是从 StringInteger.Integer 是不可变的,所以你不能在原地增加它.您必须检索当前值,增加它并将其放回原处.您正在尝试调用 wordCount.get(seq++),这没有多大意义.get() 必须在 String 中传递(对于这种 Map),你不能使用 ++ 无论如何都在不可变的 Integer 上.

The Map is from String to Integer. Integer is immutable so you can't increment it in place. You have to retrieve the current value, increment it and put it back. You're trying to call wordCount.get(seq++), which doesn't make a lot of sense. get() has to be passed in a String (for this kind of Map) and you can't use ++ on an immutable Integer anyway.

这篇关于Map<String, Integer> 中的计数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆