Java字典,Map接口

// 字典,Map接口
	public static void main(String[] args) {
		Map<String, String> hashMap = new HashMap<String, String>();
		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<String> keySet = hashMap.keySet();
		Iterator<String> 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<String> values = hashMap.values();
		Iterator<String> iterator2 = values.iterator();
		
		while (iterator2.hasNext()) {//输出Map全部的value
			String string2 = iterator2.next();
			System.out.println(string2);
		}

猜你喜欢

转载自8850702.iteye.com/blog/2282398
今日推荐