简体   繁体   中英

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

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>>();

Your code has something wrong in terms of syntax. It should be something like that:

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

public SynoniemenBeheer() {
    tree_map = new TreeMap<>();
    TreeSet<String> tree_set = new TreeSet<>(new MyComparator());
    tree_map.put("foo", tree_set);
}

And to add some elements to the already present TreeSet<> you can do something like this:

if (tree_map.get("foo") == null) { //null check and fill only if necessary
    tree_map.put("foo", new TreeSet<>());
}
tree_map.get("foo").add("foo-foo");

First you instantiate the Treemap:

TreeMap<String, TreeSet<String>> map = new TreeMap<>();

Then you instantiate the Treeset you want to put into your map:

TreeSet set = new TreeSet<String>(comparator);

Then you add the values you want to add to the set:

Collections.addAll(set, "value1","value2","value3");

Then you put the set into your map:

map.put("key", set);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM