开发者

Problem counting in Map<String, Integer>

开发者 https://www.devze.com 2022-12-19 16:37 出处:网络
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

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

So for

ACU we will get 4,

ACY we wi开发者_开发知识库ll 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++));
  }

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

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.


What you want is:

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

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.


wordCount.get(seq++) is probably the issue--try incrementing the return value of the get method (right now you're apparently attempting to increment the String argument, triggering the error. Try changing that to wordCount.get(seq)+1


Alternative solution that uses Multiset from Guava.

Multiset<String> words = HashMultiset.create();
for (String word : wordList)
    words.add(word);

for (String word : words.elementSet())
    System.out.println(word + ": " + words.count(word));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号