您将使用哪种数据结构:TreeMap或HashMap? (Java) [英] Which data structure would you use: TreeMap or HashMap? (Java)

查看:141
本文介绍了您将使用哪种数据结构:TreeMap或HashMap? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

描述| 一个Java程序,用于读取文本文件,并按字母顺序打印每个唯一的单词以及该单词在文本中出现的次数。

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.

程序应该声明一个类型为 Map< String,Integer> 的变量来存储单词和相应的频率发生。哪个具体类型呢? TreeMap< String,Number> HashMap< String,Number>

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> ?

输入应转换为小写。

一个字不包含任何这些字符: \t\ t\\\
] f。,!?:; \()'

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

示例输出|

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

备注| strong>我知道,我已经在Perl中看到了大约两行代码的优雅解决方案,但是我想用Java看到它。

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.

编辑:哦是的,使用这些结构之一(在Java中)显示一个实现是有帮助的。

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

推荐答案

TreeMap 似乎是一个no-对我而言 - 只是因为按字母顺序的要求。当迭代时,HashMap没有排序; TreeMap以自然的关键顺序迭代。

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.

编辑:我认为Konrad的评论可能建议使用HashMap,然后排序。这是很好的,因为虽然我们最初将进行N次迭代,但由于重复,我们最终将有K = N个键。我们可以节省昂贵的一点(排序),直到结束时,我们有更少的密钥,而不是按照我们去的保持排序的小但不间断的打击。

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.

说完了,我现在坚持我的答案:因为这是实现目标的最简单的方式。我们真的不知道OP对表演特别担心,但问题意味着他关心的是优雅和简洁。使用TreeMap使得这个令人难以置信的简短,这呼吁了我。我怀疑如果表现真的是一个问题,可能会有一个比TreeMap或HashMap更好的攻击方式:)

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 :)

这篇关于您将使用哪种数据结构:TreeMap或HashMap? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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