Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Exploring the Java Collection Framework Maps

Problems with the code challenge...

Hi,

Can anyone see what I am doing wrong here?

  public Map<String, Integer> getCategoryCounts() {
    Map<String, Integer> categoriesMap = new HashMap<String, Integer>();
    for (BlogPost blogpost : getPosts()) {
      for (String category : blogpost.getCategory()) {
        int count++;
        categoriesMap(category, count);
      }
    }
    return categoriesMap;
  }

2 Answers

Should be something like this. Hope this helps.

import java.util.Map;
import java.util.HashMap;

public Map<String, Integer> getCategoryCounts() {
    Map<String, Integer> categoriesMaps = new HashMap<String, Integer>();
    for (BlogPost blogPost : mPosts) {
        String category = blogPost.getCategory();
        Integer count = categoriesMaps.get(category);
        if (count == null) {
          count = 0;
        }
        count++;
        categoriesMaps.put(category, count);
    }
    return categoriesMaps;
  }

By using int count++; you're creating a new count of zero every loop and incrementing, so the word count is always 1. What you should do is retrieve the count from the map first, make sure it's not null, then increment and store it back.

Hi! Thanks for helping.

I've changed the code to this:

    public Map<String, Integer> getCategoryCounts() {
    Map<String, Integer> categoriesMap = new HashMap<String, Integer>();
    for ( BlogPost blogPost : getPosts() ) {
      for ( String category : blogPost.getCategory()) {
        count++;
        categoriesMap(category, count);
      }
    }
    return categoriesMap;
  }

But I get these errors:

./com/example/Blog.java:20: error: for-each not applicable to expression type for ( String category : blogPost.getCategory()) { ^ required: array or java.lang.Iterable found: String ./com/example/Blog.java:22: error: cannot find symbol categoriesMap(category, count); ^ symbol: method categoriesMap(String,int) location: class Blog Note: JavaTester.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 2 errors

BlogPost.getCategory() returns a String not a Collection, so there is only one category per post. to the inner for loop is unnecessary.