Search code examples
javasortinguniquetreemap

Generate unique key to avoid overwriting in TreeMap


I have a TreeMap<Long, String> that contains tuples of <FileSize, FileName> as I need to sort it by file sizes. The ordering works perfectly.

Now I just have the problem, that a new file, that has the same size as another one that already exists in the Map, would overwrite the old entry with this new file name.

I just tried to add an incrementing counter value to the TreeMap key, by changing the the TreeMap to TreeMap<String, String> and filling the key by <fileSize#counter, fileName>. Then the problem was the ordering of the keys, because a String e.g. 9#1 would come between 89#1 and 90#1 which is wrong, because the fileSize is only 9 (and therefore should came before 89 and 90)!

Then I wrote a custom Comparator which is able to sort it again by the fileSize (by removing the second part with the counter value), but then the entries are overwritten again, if the first part of the key (fileSize) is the same (independent of the #counter value).

Here is my code:

TreeMap<String, String> fileNamesAndSizes = new TreeMap<String, String>(new Comparator<String>() {
    public int compare(String o1, String o2) {
        Long key1 = Long.valueOf(o1.split("#")[0]);
        Long key2 = Long.valueOf(o2.split("#")[0]);

        return key1.compareTo(key2);
    }
});

How to get unique keys in my TreeMap without overwriting existing values and get a correct (ascending fileSize) ordering?

Thank you!


Solution

  • I would just try to store them in a such structure:

    TreeMap<Long, Set<String>> map; //Long file Size, Set <-- file name(s)
    

    now to add a new file:

    if(!map.contains(key)){  //key the size of the file
     Set<String> set = new HashSet<String>();
     map.put(key,set);
    }
    map.get(key).add(set);
    

    to retrive you need to go through each value entry:

    for(Map<Long,Set<String>> entry  : map.entrySet()){
    
       for(String s : entry.getValue()){
        System.out.println(entry.getKey() + " : " + s);
       }
    }