[英]key value pair implementation in java?
Java 中有類似KeyValuePair
東西嗎?
我有一個非常長的以下類元素列表:
public class Foo {
int id;
Set<String> items;
}
存儲在這里:
LinkedList<Foo> myList;
每次我搜索一個項目時,我都會遍歷列表並搜索該項目,但這需要很多時間。 我想做這樣的事情:
myList.get(123) => items of the Foo with id = 123
為此,您可以在 Java 中使用Map
。 它將允許鍵值對。
Map<Integer,Set<String>> map = new HashMap<Integer,Set<String>>();
將項目添加到地圖
Set<String> set = new HashSet<String>();
set.add("ABC");
set.add("DEF");
map.put(123,set);
從地圖獲取項目
map .get(123) will give Set<String> associated with id 123
嘗試一些java.util.Map
。
更多信息: 這里
我認為MultiMap<Integer,String>
適合您的情況。
您將需要一個所謂的 MultiMap,默認情況下 java 沒有,但您始終可以為此目的使用 Map。
嘗試使用HashMap<Integer, Set<String>>
導入 java.util.*;
班級溫度{
public static void main(String[] args){
Map<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"anand");
map.put(2,"bindu");
map.put(3,"cirish");
System.out.println(1+" = "+map.get(1));
System.out.println(2+" = "+map.get(2));
System.out.println(3+" = "+map.get(3));
Map<String,Integer> map1 = new HashMap<String,Integer>();
map1.put("anand",1);
map1.put("bindu",2);
map1.put("cirish",3);
System.out.println("anand = "+map1.get("anand"));
System.out.println("bindu = "+map1.get("bindu"));
if(map1.get("cirish") != null){
System.out.println("cirish = "+map1.get("cirish"));
}
if(map1.get("dinesh") != null){
System.out.println("cirish = "+map1.get("dinesh"));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.