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

查看:185
本文介绍了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 0
ACU 1
ACU 1
ACU 1
ACY 1
ACY 2
AER 2
AER 3
AER 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));
}

请帮助我。感谢所有。

推荐答案

你想要的是:

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

地图 String 整数整数是不可变的,所以你不能增加它的位置。您必须检索当前值,将其递增并放回。你试图调用 wordCount.get(seq ++),这没有什么意义。 get()必须在 String 中传递(对于这种 Map ),并且您无法使用不可变的整数中的 ++

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&lt; String,Integer中的问题计数&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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