---
title: "Java字典,Map接口"
author: "8850702"
date: "2016-03-12T18:17:34Z"
tags: []
categories: ["移动开发"]
slug: "java-map"
draft: false
lastmod: "2016-03-12T18:17:34Z"
id: 2282398
url: "https://8850702.iteye.com/blog/2282398"
---

\[code="java"] // 字典,Map接口 public static void main(String\[] args) { Map hashMap = new HashMap(); hashMap.put("1", "Brock"); hashMap.put("2", "chris"); hashMap.put("3", "ood");// 增加元素 String string = hashMap.get("3");// 取出元素 System.out.println(string); //判断字典里面，有没有这个key System.out.println(hashMap.containsKey("1") ? "有这个key" : "没这个key"); //判断字典里面，有没有这个value System.out.println(hashMap.containsValue("chris") ? "有这个value" : "没有这个value"); //遍历输出Map的key //利用Map接口的方法keySet(),得到一个Set(全部key的集合) //再用Set的iterator()方法，得到Iterator接口 Set keySet = hashMap.keySet(); Iterator iterator = keySet.iterator(); while (iterator.hasNext()) {//输出Map全部的key String string2 = iterator.next(); System.out.println(string2); } //遍历输出Map的value //利用Map接口的方法values(),得到一个Collection(全部value的集合) //再用Collection的iterator()方法，得到Iterator接口 Collection values = hashMap.values(); Iterator iterator2 = values.iterator(); while (iterator2.hasNext()) {//输出Map全部的value String string2 = iterator2.next(); System.out.println(string2); } \[/code]