HashMap使用范例

HashMapDemo.java

package corejava8.structure;

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
public static void main(String[] argv) {
// Construct and load the hash. This simulates loading a
// database or reading from a file, or wherever the data is.

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

// The hash maps from company name to address.
// In real life this might map to an Address object...
map.put("Adobe", "Mountain View, CA");
map.put("IBM", "White Plains, NY");
map.put("Learning Tree", "Los Angeles, CA");
map.put("Microsoft", "Redmond, WA");
map.put("Netscape", "Mountain View, CA");
map.put("O'Reilly", "Sebastopol, CA");
map.put("Sun", "Mountain View, CA");

// Two versions of the "retrieval" phase.
// Version 1: get one pair's value given its key
// (presumably the key would really come from user input):
String queryString = "O'Reilly";
System.out.println("You asked about " + queryString + ".");
String resultString = map.get(queryString);
System.out.println("They are located in: " + resultString);
System.out.println();

// Version 2: get ALL the keys and values
// (maybe to print a report, or to save to disk)
for( String key : map.keySet()) {
System.out.println("Key " + key + "; Value " + map.get(key));
}

// Version 3: Same but using a Map.Entry lambda
map.entrySet().forEach(mE ->
System.out.println("Key + " + mE.getKey() + "; Value " +mE.getValue()));
}
}

运行结果:
You asked about O'Reilly.
They are located in: Sebastopol, CA

Key IBM; Value White Plains, NY
Key Learning Tree; Value Los Angeles, CA
Key O'Reilly; Value Sebastopol, CA
Key Microsoft; Value Redmond, WA
Key Adobe; Value Mountain View, CA
Key Sun; Value Mountain View, CA
Key Netscape; Value Mountain View, CA
Key + IBM; Value White Plains, NY
Key + Learning Tree; Value Los Angeles, CA
Key + O'Reilly; Value Sebastopol, CA
Key + Microsoft; Value Redmond, WA
Key + Adobe; Value Mountain View, CA
Key + Sun; Value Mountain View, CA
Key + Netscape; Value Mountain View, CA
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值