Search code examples
javacollectionstreemaptreeset

Java collections, use treeset as value for treemap


I'd like to create a collection of data using a TreeMap implementation with String as key and a TreeSet as value sorted with an own Mycomparator instance. It can not contain duplicate values hence the TreeMap.

private TreeMap<String, TreeSet<String>> tree_map = null;

public constructorTreeMap() {
    tree_map = new TreeSet<String>()new MyComparator();

I can't get the instantiation right, how should I do that?

And how can I add multiple Strings to the TreeSet afterwards?

Thanks any help is welcome =)


Solution

  • I hope following example clears things up a bit:

    TreeMap<String, TreeSet<String>> treeMap = null;
    // First you instantiate your TreeMap
    treeMap = new TreeMap<String, TreeSet<String>>();
    
    // Next you create your TreeSet value which you can instantiate with your comparator
    TreeSet<String> value = new TreeSet<String>(myComparator);
    value.add("FOO");
    value.add("BAR");
    // Then you can insert that TreeSet as value in your TreeMap
    treeMap.put("your-string-key", value);
    

    You might want to consider using the Set<String> interface class when instantiating your treeMap though, which makes it more generic:

    TreeMap<String, Set<String>> treeMap = new TreeMap<String, Set<String>>();