简体   繁体   English

数据结构集,列表,地图还是树?

[英]Data Structure Set, List, Map or Tree?

I am trying to choose a Java data structure with the following properties 我正在尝试选择具有以下属性的Java数据结构

Key: Long 键:长

Value: Set 值:设定

Is there a structure that I can index into and add values to the Set? 有没有可以索引并为Set添加值的结构?

For example say I have the object <1, [a,b,c]> and I want to add d this so that the output is <1, [a,b,c,d]>? 例如,假设我有对象<1,[a,b,c]>,我想将此添加d,以便输出为<1,[a,b,c,d]>?

Can this be easily done in java? 可以在Java中轻松完成吗?

If you are able to use a third party library, Guava has Multimaps, which make it easy to store multiple values for a single key. 如果您能够使用第三方库,则Guava拥有Multimaps,可以轻松地为单个键存储多个值。

For example: 例如:

    import com.google.common.collect.HashMultimap;

    HashMultimap<Long, String> multimap = HashMultimap.create();
    multimap.put(1L, "a");
    multimap.put(1L, "b");
    multimap.put(1L, "c");
    multimap.put(1L, "d");

See the docs . 请参阅文档

As others have stated, you will be best served by a Map<Long, Set<String>> . 正如其他人所述,最好使用Map<Long, Set<String>> In your example: 在您的示例中:

Map<Long, Set<String>> myMap = new HashMap<Long, Set<String>>(); 
Set<String> initialSet = new HashSet<String>();
initialSet.add("a");
initialSet.add("b");
initialSet.add("c");
myMap.put(1, initialSet);
myMap.get(1).add("d"); // to add the "d"

I have the object <1, [a,b,c]> and I want to add d this so that the output is <1, [a,b,c,d]> ? 我有对象<1, [a,b,c]> ,我想添加d以便输出为<1, [a,b,c,d]>

Map<Long, Set<Character>

would work good 会很好

是的,地图可以工作。

Map yourmap = new HashMap<Long, List<String>>();

Just use: 只需使用:

HashMap<Long, String> map = new HashMap<Long, ArrayList<String>>();

If you want to add something to it just 如果你想添加一些东西

ArrayList<String> list = map.get(KEY_YOU_WANT_TO_CHECK);
if(list == null){
    list = new ArrayList<String>();
    list.add(STRING_YOU_WANT_TO_ADD);
    map.put(KEY_YOU_WANT_TO_CHECK,list);
}else{
    list.add(STRING_YOU_WANT_TO_ADD);
}

Of course you can replace ArrayList with HashSet also with Vector and TreeSet 当然,您也可以使用VectorTreeSet HashSet替换为ArrayList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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