问题地图&LT计数,字符串,整数> [英] Problem counting in Map<String, Integer>

查看:100
本文介绍了问题地图&LT计数,字符串,整数>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个<一个href=\"http://stackoverflow.com/questions/2194215/problem-in-count-field-in-arraylist-and-save-it\">question关于计数次数的字是在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的错误,我试图修改code工作
但我发现了不正确的数字。

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

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

请帮我在这一个。感谢所有。

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

地图字符串整数整数是不变的,所以你不能到位加一。你必须获取当前值,增加它并把它放回去。你试图调用 wordCount.get(SEQ ++),不使有很大的意义。 的get()有一个字符串(对于这种地图<中/传递code>),你不能使用 ++ 上一个不可变整数反正。

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.

这篇关于问题地图&LT计数,字符串,整数&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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