Map可以保存一对儿数据,分别是“键”和对应的“值”
- public class Test_HashMap {
- public static void main(String[] args) {
- Map<String, String> map = new HashMap<String, String>();
- map.put("第一首", "我的太阳");
- map.put("第二首", "夜曲");
- map.put("第三首", "流水");
- map.put("第五首", "高山");
- map.put("第六首", "渔樵");
- String str = map.get("第二首"); // 获取 键为 第二首 的 数值
- System.out.println(str);
- // 判断键与值是否存在
- if(map.containsKey("第三首")){
- System.out.println("存在,歌曲为:"+map.get("第三首"));
- }
- if (map.containsKey("第四首")) {
- System.out.println("存在");
- }else {
- System.out.println("第四首不存在");
- }
- // 得到所有的键
- Set<String> s = map.keySet();
- Iterator<String> i = s.iterator();
- while (i.hasNext()) {
- System.out.println(i.next());
- }
- // 得到所有的值
- Collection<String> cs = map.values();
- i = cs.iterator();
- while (i.hasNext()) {
- // 获得所有值
- System.out.println(i.next());
- }
- }
- }
复制代码 |
|