Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which data structure would you use: TreeMap or HashMap? (Java) [duplicate]

Description | A Java program to read a text file and print each of the unique words in alphabetical order together with the number of times the word occurs in the text.

The program should declare a variable of type Map<String, Integer> to store the words and corresponding frequency of occurrence. Which concrete type, though? TreeMap<String, Number> or HashMap<String, Number> ?

The input should be converted to lower case.

A word does not contain any of these characters: \t\t\n]f.,!?:;\"()'

Example output |

 Word            Frequency   a                 1   and               5   appearances       1   as                1          .          .          . 

Remark | I know, I've seen elegant solutions to this in Perl with roughly two lines of code. However, I want to see it in Java.

Edit: Oh yeah, it be helpful to show an implementation using one of these structures (in Java).

like image 478
JohnZaj Avatar asked Nov 19 '08 15:11

JohnZaj


People also ask

Does Java TreeMap allow duplicates?

A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.

Does TreeMap remove duplicates?

TreeMap Features It allows only distinct keys. Duplicate keys are not possible.

When would a TreeMap be preferable to a HashMap?

It provides a performance of O(1) , while TreeMap provides a performance of O(log(n)) to add, search, and remove items. Hence, HashMap is usually faster. A TreeMap uses memory way more effective so it is a good Map implementation for you if you are not sure of elements quantity that have to be stored in memory.

Why would anyone use TreeMap over HashMap?

TreeMap provides a performance of O(log(n)) for most operations like add(), remove() and contains() A Treemap can save memory (in comparison to HashMap) because it only uses the amount of memory needed to hold its items, unlike a HashMap which uses contiguous region of memory.


2 Answers

TreeMap seems a no-brainer to me - simply because of the "in alphabetical order" requirement. HashMap has no ordering when you iterate through it; TreeMap iterates in the natural key order.

EDIT: I think Konrad's comment may have been suggesting "use HashMap, then sort." This is good because although we'll have N iterations initially, we'll have K <= N keys by the end due to duplicates. We might as well save the expensive bit (sorting) until the end when we've got fewer keys than take the small-but-non-constant hit of keeping it sorted as we go.

Having said that, I'm sticking to my answer for the moment: because it's the simplest way of achieving the goal. We don't really know that the OP is particularly worried about performance, but the question implies that he's concerned about the elegance and brevity. Using a TreeMap makes this incredibly brief, which appeals to me. I suspect that if performance is really an issue, there may be a better way of attacking it than either TreeMap or HashMap :)

like image 178
Jon Skeet Avatar answered Sep 24 '22 16:09

Jon Skeet


TreeMap beats HashMap because TreeMap is already sorted for you.

However, you might want to consider using a more appropriate data structure, a bag. See Commons Collections - and the TreeBag class:

This has a nice optimised internal structure and API:

bag.add("big") bag.add("small") bag.add("big") int count = bag.getCount("big") 

EDIT: The question of HashMap vs TreeMap performance was answered by Jon - HashMap and sort may be quicker (try it!), but TreeBag is easier. The same is true for bags. There is a HashBag as well as a TreeBag. Based on the implementation (uses a mutable integer) a bag should outperform the equivalent plain map of Integer. The only way to know for sure is to test, as with any performance question.

like image 44
JodaStephen Avatar answered Sep 24 '22 16:09

JodaStephen