Java TreeMap:从单个键中检索多个值

时间:2012-11-13 04:46:48

标签: java key treemap treeset

我正在尝试从TreeMap中的单个键中检索多个值。我们的想法是每个密钥都链接到多个值,并且应该是可搜索的。现在我遇到的麻烦是,当我只能从密钥中获取一个值时。

键是一个String,值是一个名为Song的自定义对象。歌曲包含多个元素。目标是从每首歌曲中逐字逐句提取歌词,并将每个单词用作关键词。然后键将链接到包含键的每个乐曲(值)。

我一直在搜索StackOverFlow和网页上的提示,我已经看过一些,但没有任何直接解决我的绊脚石。我看到的一个想法是将值更改为某种数组或列表。当我的大脑恢复精神时,明天我可能会尝试。

无论如何,提前感谢任何提示和建议。是的,这是家庭作业。不,我没有标记是因为我被告知家庭作业标签不再常用。

代码:

public class SearchByLyricsWords {
   private static Song[] songs;

   private static TreeMap<String, Song> lyricsTreeMap = new TreeMap<String, Song>();

   private static TreeSet<String> wordsToIgnoreTree = new TreeSet<String>();
   private static File wordsToIgnoreInput = new File("ignore.txt");
   private static String wordsToIgnoreString;
   private static String[] wordsToIgnoreArray;

   private Song[] searchResults;  // holds the results of the search
   private ArrayList<Song> searchList = new ArrayList<Song>();  

public SearchByLyricsWords(SongCollection sc) throws FileNotFoundException {

  // Create a string out of the ignore.txt file
  Scanner scanInputFile = new Scanner(wordsToIgnoreInput);
  String ignoreToken = scanInputFile.next();
  ignoreToken.toLowerCase();
  wordsToIgnoreString = ignoreToken + " ";

  while (scanInputFile.hasNext()) {
     ignoreToken = scanInputFile.next();
     wordsToIgnoreString = wordsToIgnoreString + ignoreToken + " ";
  }

  // Split the string created from ignore.txt 
  wordsToIgnoreArray = wordsToIgnoreString.split("[^a-zA-Z]+");

  // Fill a TreeSet from the wordsToIgnoreArray
  for (int i = 0; i < wordsToIgnoreArray.length; i++) {
     ignoreToken = wordsToIgnoreArray[i];
     wordsToIgnoreTree.add(ignoreToken);
  }

  // Fill TreeMap with lyrics words as the key, Song objects as the value
  songs = sc.getAllSongs();

  for (int j = 0; j < songs.length; j++) {
     Song currentSong = songs[j];
     String lyrics = currentSong.getLyrics();         
     TreeSet<String> lyricsFound = new TreeSet<String>();

     String lyricsToken;
     String[] songLyricsArray;
     songLyricsArray = lyrics.split("[^a-zA-Z]+");

     for (int k = 0; k < songLyricsArray.length; k++) {
        lyricsToken = songLyricsArray[k];

        if (lyricsToken.length() <= 1) {
           continue;
        }

        lyricsFound.add(lyricsToken);
     }

     lyricsFound.removeAll(wordsToIgnoreTree);

     Iterator<String> iterator = lyricsFound.iterator();

     while(iterator.hasNext()) {
        String currentWord = (String)iterator.next();
        lyricsTreeMap.put(currentWord, currentSong);
     }

     //System.out.println(lyricsTreeMap); // testing only
  }
}


public Song[] search(String lyricsWords) {

  lyricsWords = lyricsWords.toLowerCase();
  TreeSet<String> searchTree = new TreeSet<String>();
  String searchToken;
  String[] lyricsWordsSearch = lyricsWords.split("[^a-zA-Z]+");

  for (int l = 0; l < lyricsWordsSearch.length; l++) {
     searchToken = lyricsWordsSearch[l];

     if (searchToken.length() <= 1) {
        continue;            
     }
     searchTree.add(searchToken);
  }
  searchTree.removeAll(wordsToIgnoreTree);

  Iterator<String> searchIterator = searchTree.iterator();

  while(searchIterator.hasNext()) {
     String currentSearchWord = (String)searchIterator.next();
     Collection<Song> lyricsTreeCollection = lyricsTreeMap.values();

     while (lyricsTreeMap.containsKey(currentSearchWord) == true) {

        Iterator collectionIterator = lyricsTreeCollection.iterator();

        while(collectionIterator.hasNext() && collectionIterator.next() == currentSearchWord) {

           Song searchSong = lyricsTreeMap.get(currentSearchWord);
           searchList.add(searchSong);          
        }
     }           
  }
  searchResults = searchList.toArray(new Song[searchList.size()]);

  Arrays.sort(searchResults);

  return searchResults;
}

3 个答案:

答案 0 :(得分:7)

TreeMap每个密钥只保留一个值as with all Map implementations

  

地图不能包含重复的键;每个键最多可以映射一个值。

您的替代方案包括

  • 使用TreeMap<String, List<Song>>代替,并手动处理List值并保持更新
  • 使用来自Guava的e.g. a TreeMultimap,其中(或多或少)像TreeMap<K, TreeSet<V>>一样运作,除了好多了。 (披露:我向Guava捐款。)

答案 1 :(得分:1)

我认为你应该将你的结构设置为

Map<String, Set<Song>>

此处Set用作内部Collection类,而不是List。因为它会自动省略场景的redundent值。

答案 2 :(得分:1)

您需要使用此格式初始化地图并设置:

Map<String, TreeSet<Song>>=new Map<String,treeSet<Song>>();

您需要多个for循环才能首先通过歌曲集循环,然后将Map键插入Map中。 像这样:

    for(Song temp:songs){
       for(String word:temp.getLyrics().toLowerCase().split("[^a-zA-Z]+"){
             if(lyricsTreeMap.containsKey(word)){
                  lyricsTreeMap.get(word).add(temp);
    }