我正在用Java编写一个简单的编辑文本.当用户打开它时,将打开一个文件JTabbedPane.我做了以下保存打开的文件:
HashMap<String, Tab> hash = new HashMap<String, Tab>();
哪里Tab会收到价值,例如:File file, JTextArea container, JTabbedPane tab.
我有一个叫做的课Tab:
public Tab(File file, JTextArea container, JTabbedPane tab)
{
this.file = file;
this.container = container;
this.tab = tab;
tab.add(file.getName(), container);
readFile();
}
Run Code Online (Sandbox Code Playgroud)
现在,在这个SaveFile类中,我需要获取Tab存储在中的值HashMap.我怎样才能做到这一点?
Boh*_*ian 82
要从地图中获取所有值:
for (Tab tab : hash.values()) {
// do something with tab
}
Run Code Online (Sandbox Code Playgroud)
要从地图中获取所有条目:
for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}
Run Code Online (Sandbox Code Playgroud)
要处理所有值:
hash.values().forEach(tab -> /* do something with tab */);
Run Code Online (Sandbox Code Playgroud)
处理所有条目:
hash.forEach((key, tab) -> /* do something with key and tab */);
Run Code Online (Sandbox Code Playgroud)
Pra*_*bhu 25
Map内部由Map.Entry对象组成.每个Entry包含key和value.要从条目中获取键和值,请使用访问器和修改器方法.
如果你想得到给values定key,使用get()方法和插入值,使用put()方法.
#Define and initialize map;
Map map = new HashMap();
map.put("USA",1)
map.put("Japan",3)
map.put("China",2)
map.put("India",5)
map.put("Germany",4)
map.get("Germany") // returns 4
Run Code Online (Sandbox Code Playgroud)
如果要从地图中获取键集,可以使用keySet()方法
Set keys = map.keySet();
System.out.println("All keys are: " + keys);
// To get all key: value
for(String key: keys){
System.out.println(key + ": " + map.get(key));
}
Run Code Online (Sandbox Code Playgroud)
通常,要从地图获取所有键和值,您必须按以下顺序执行序列:
Hashmap为使用方法MapSet获取条目集:Mapentryset()Set st = map.entrySet();Iterator it = st.iterator();Map.Entry从迭代器中获取:Map.Entry entry = it.next();getKey()和getValue()方法Map.Entry得到键和值.// Now access it
Set st = (Set) map.entrySet();
Iterator it = st.iterator();
while(it.hasNext()){
Map.Entry entry = mapIterator.next();
System.out.print(entry.getKey() + " : " + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
简而言之,直接使用iterator
for(Map.Entry entry:map.entrySet()){
System.out.print(entry.getKey() + " : " + entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
小智 12
你给1美元,它给你一个芝士汉堡.你给String,它给你Tab.使用HashMap的GET方法来获得你想要的东西.
HashMap.get("String");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
329275 次 |
| 最近记录: |