我当前的项目让我们在 Java 中使用 TreeSet 和 TreeMap,输入数组包含从文本文件中读取的 10514 个 Song 元素。每首歌曲都包含一个艺术家、标题和歌词字段。该项目的目的是使用集合和地图对歌词进行快速搜索。
首先,我遍历输入的 Song 数组,访问歌词字段并创建一个 Scanner 对象以使用以下代码遍历歌词: commonWords
是不应该是键的单词的 TreeSet,并且lyricWords
是单词到 Songs 的整体映射。
public void buildSongMap() {
for (Song song:songs) {
//method variables
String currentLyrics= song.getLyrics().toLowerCase();
TreeSet<Song> addToSet=null;
Scanner readIn= new Scanner(currentLyrics);
String word= readIn.next();
while (readIn.hasNext()) {
if (!commonWords.contains(word) && !word.equals("") && word.length()>1) {
if (lyricWords.containsKey(word)) {
addToSet= lyricWords.get(word);
addToSet.add(song);
word=readIn.next();
} else
buildSongSet(word);
} else
word= readIn.next();
}
}
为了构建歌曲集,我使用以下代码:
public void buildSongSet(String word) {
TreeSet<Song> songSet= new TreeSet<Song>();
for (Song song:songs) {
//adds song to set
if (song.getLyrics().contains(word)) {
songSet.add(song);
}
}
lyricWords.put(word, songSet);
System.out.println("Word added "+word);
}
现在,由于 buildSongSet 是从循环内部调用的,因此创建地图需要 N^2 次执行。当输入数组是 4 首歌曲时,搜索运行非常快,但是当使用 10514 个元素的完整数组时,在具有 6 GiB RAM 的 2.4GHz 机器上构建地图可能需要 15+ 分钟。我该怎么做才能使这段代码更有效率?不幸的是,减少输入数据不是一种选择。