Map集合常用实现类

1、HashMap:无序

package com.xn.ffri;

import java.util.HashMap;

public class Fri06 {
	public static void main(String[] args) {
		//HashMap
		//KV键值对集合,key唯一,value允许重复
		HashMap<String, Integer> cityMap=new HashMap<String, Integer>();
		//put()方法:添加键值对
		//如果key不存在,键返回null
		System.out.println(cityMap.put("X西安",11111));
		System.out.println(cityMap.put("C长沙",22222));
		System.out.println(cityMap.put("X厦门",33333));
		System.out.println(cityMap.put("W武汉",44444));
		//如果key存在,则保存新value,返回旧value
		System.out.println(cityMap.put("X西安",11112));
		//
		int value1=cityMap.get("C长沙");
		System.out.println("C长沙 ==>"+value1);
		
		Integer value3=cityMap.get("G贵阳");
		System.out.println("G贵阳 ==>"+value3);
		
		int value2=cityMap.get("G贵阳");
		System.out.println("G贵阳 ==>"+value2);
	}
}

2、LinkedHashMap:有序

package com.xn.ffri;

import java.util.HashMap;
import java.util.LinkedHashMap;

public class Fri09 {
	public static void main(String[] args) {
		String str="hfdshsvhsuvhsdoarfregerjcxxoivpohytj";
		//无序
//		HashMap<String, Integer> map=new HashMap<String,Integer>();
		//有序
		LinkedHashMap<String,Integer> map= new LinkedHashMap<String, Integer>();
		for(int i=0;i<str.length();i++) {
			String key=str.substring(i,i+1);
			//判断key是否存在
			if(map.containsKey(key)) {
				//该字符(key)存在
				map.put(key,map.get(key)+1);
			}else {
				//该字符(key)不存在
				map.put(key, 1);//默认次数为1
			}
		}
		System.out.println(map);
	}
}

3、TreeMap:按照key自动排序

package com.xn.ffri;

import java.util.Comparator;
import java.util.TreeMap;
import java.util.Map.Entry;

public class Fri10 {
	public static void main(String[] args) {
		//TreeMap:按照key自动排序,通过key进行比较后排序
		//HashMap<string,String>map new HashMap<String,String>();
		//TreeMap:按照key自动排序,通过key进行比较后排序

		TreeMap<String,String> map=new TreeMap<String,String>( new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				int n1=Integer.parseInt(o1.substring(2));
				int n2=Integer.parseInt(o2.substring(2));
				return n1-n2;
			}
		});
		map.put("FC104", "A1");
		map.put("FC1612", "A2");
		map.put("FC1245", "A3");
		map.put("FC187", "A4");
		map.put("FC14599", "A5");
		map.put("FC167", "A6");
		map.put("FC1469", "A7");
		map.put("FC1989", "A8");
		map.put("FC1528", "A9");
		
		for(Entry<String, String> entry : map.entrySet()) {
			System.out.println(entry);
		}
	}
}

4、Hashtable:无序;线程安全,性能低;不允许使用null做key;不允许使用null做value

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值