java java中的键值对实现?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16733138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:49:33  来源:igfitidea点击:

key value pair implementation in java?

java

提问by gurehbgui

Is there something like a KeyValuePairin Java?

KeyValuePairJava中有类似的东西吗?

I have a Very long list of elements of the following class:

我有一个很长的以下类的元素列表:

public class Foo {
    int id;
    Set<String> items;
}

which is stored here:

存储在这里:

LinkedList<Foo> myList;

each time I search for a item, I iterate over the list and search for the Item, but this takes to much time. I want to do something like this:

每次我搜索一个项目时,我都会遍历列表并搜索该项目,但这需要很多时间。我想做这样的事情:

myList.get(123) => items of the Foo with id = 123

回答by PSR

You can use Mapin Java for that purpose. It will allow key, value pairs.

Map为此,您可以在 Java 中使用。它将允许键值对。

Map<Integer,Set<String>> map = new HashMap<Integer,Set<String>>();

Adding item to map

将项目添加到地图

Set<String> set = new HashSet<String>();
      set.add("ABC");
      set.add("DEF");
      map.put(123,set);

Getting item from map

从地图中获取物品

  map .get(123)  will give  Set<String>  associated  with id  123

回答by Konstantin Yovkov

Try some impelementation of java.util.Map.

尝试对java.util.Map.

More info: here

更多信息:这里

回答by Petros Tsialiamanis

I think the MultiMap<Integer,String>is suitable in your case.

我认为MultiMap<Integer,String>适合您的情况。

回答by AlexWien

you would need a so called MultiMap, java dont has that by default, but you always can use a Map for that purpose.

您将需要一个所谓的 MultiMap,默认情况下 java 没有,但您始终可以为此目的使用 Map。

Try using a HashMap<Integer, Set<String>>

尝试使用 HashMap<Integer, Set<String>>