aspose file tools
The moose likes Beginning Java and the fly likes adding value to TreeMap Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "adding value to TreeMap" Watch "adding value to TreeMap" New topic
Author

adding value to TreeMap

Tom Mordon
Ranch Hand

Joined: Apr 26, 2012
Posts: 30
I have a TreeMap:


In the method if the token is found I'm supposed to add to the List but the compiler does not like my code. How can I add the tokenOccurence to the list in the TreeMap? This one area has been stumping be for hours.

Greg Charles
Bartender

Joined: Oct 01, 2001
Posts: 2542
    
  10

Hi Tom,

Welcome to JavaRanch! First, a quick nag: please use code tags when posting code. There's a Code button above the edit window, which makes it really easy to do.

Now, TreeMap, like all maps lets you add a key, value pair and the method is called put(key, value). There is no TreeMap.add() method, so what you've shown us wouldn't even compile. I'm not completely sure what you are trying to do, but if you want to add an integer like tokenOccurence to a map, you have to covert it to an Object, like by calling "new Integer(tokenOccurence)".
Winston Gutkowski
Bartender

Joined: Mar 17, 2011
Posts: 4756
    
    7

Tom Mordon wrote:In the method if the token is found I'm supposed to add to the List but the compiler does not like my code. How can I add the tokenOccurence to the list in the TreeMap? This one area has been stumping be for hours.

I'm not quite sure exactly what it is you're trying to do. Are you trying to count the number of times a particular token appears in a piece of input?

If so:
(a) You don't need a List.
(b) You need a counter of some sort, and unfortunately, Integer isn't the ideal class because it's immutable.

If indeed that is what you want to do, my suggestion would be to try a TreeList<String, AtomicInteger> (AtomicInteger is mutable).

Winston


Isn't it funny how there's always time and money enough to do it WRONG?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32694
    
    4
You can’t add directly to the set of keys. I would suggest you cheat, but I won’t tell you which section of the Java™ Tutorials you will find a very similar example in.
The problem about Integer (as you already know) is that it is immutable. But you can’t store ints in Collections. So you have to use boxing and unboxing if you want to do any arithmetic. You will have to use the atomic version if you are multi-threading.
suraj aryan
Greenhorn

Joined: Nov 19, 2010
Posts: 13
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: adding value to TreeMap
 
Similar Threads
How to add elements from a file into an Array List
treemap
treemap
Can I have a list in tree map?
String Tokenizer