HasMap的遍历与map集合的定义和方法

Map集合的定义

数组的元素类型是Node<K,V>,Node<K,V>继承自Map.Entry<K,V>,表示键值对映射。

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        //构造函数 ( Hash值键值下一个节点 )
        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }

Map集合的初始化

value存数组

HashMap<Integer,String[]> columnValueList = new HashMap<Integer,String[]>();
HashMap<String,String> primaryMap = new HashMap<String,String>();
primaryMap.put(fieldName, fieldOrder.toString());
	String[] columnValue = new String[3];
	columnValue[0]=fieldName;
	columnValue[2]=fieldDataType;
	columnValueList.put(fieldOrder-1,columnValue);

value存不同类型的集合

List<HashMap<String, Object>> dataList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> Data = new HashMap<String, Object>();
		String  ageId = null;
		String sql ="select * from gl a where substr(a.xl_time,0,10)=to_char(sysdate,'yyyy-mm-dd') and a.user=?";
		List<IBean> IBeans = query(sql,userId);
		for(int i=0;i<IBeans.size();i++){
			ageId = String.valueOf(ryIBeans.get(i).get("ID"));
			List<IBean> cList = (List<IBean>) Data.get(coverageId);
			if(cList==null){
				cList = new ArrayList<IBean>();
			}
			cList.add(IBeans.get(i));
			Data.put(coverageId,cList);
		}
		Set<String> keys = Data.keySet();
		pointData.put("pointsKey", keys);
		dataList.add(Data);
		dataList.add(intData);
		return dataList;
	}

一、iterator()遍历Map集合

1、for循环遍历

	StringBuilder updateSqlValue = new StringBuilder();
    HashMap<Integer,String[]> columnValueList = new HashMap<Integer,String[]>();
	StringBuilder paramkey=new StringBuilder();
	StringBuilder paramval=new StringBuilder();
     HashMap<String,String> primaryMap = new HashMap<String,String>();

for (Iterator<Entry<Integer, String[]>> it = columnValueList.entrySet().iterator(); it.hasNext(); ) {
Entry<Integer, String[]> entry = (Entry<Integer, String[]>) it.next();
String[] entryValue = entry.getValue();
paramkey.append(",").append(entryValue[0]);
paramval.append(",").append(entryValue[1]);
				}

for (Iterator<Entry<String, String>> pm = primaryMap.entrySet().iterator(); pm.hasNext(); ) {
	Entry<String, String> entry = (Entry<String, String>) pm.next();
	if(templateActionField == null){
	paramPrimarykey.append(",").append(entry.getKey());
	String  pkVal = CommonUtils.getUUID();
	paramSubval.append(",").append("'"+pkVal+"'");
	primaryMapVal.add(pkVal);
}

2、while遍历

	public static void main(String[] args) {
		HashMap<String,Student> hashMap=new HashMap<String,Student>();
		hashMap.put("1号", new Student("张三",10));
		hashMap.put("2号", new Student("李四",11));
		hashMap.put("3号", new Student("王五",12));
		
		Student s=hashMap.get("1号");
		System.out.println(s);
		
		Iterator<String> it=hashMap.keySet().iterator(); // 获取key的集合 ,再获取迭代器
		while(it.hasNext()){
			String key=it.next(); // 获取key
			Student student=hashMap.get(key); // 获取值
			System.out.println("key="+key+",value="+student);
		}
	}

二、entrySet()遍历map集合

		Map<String, List<FastEntryVO>> fastEntryMap = getFastEntryDtoMap(fastEntryList);
		List<FastEntryDto> fastEntryDtoList = new ArrayList<FastEntryDto>(1);
		FastEntryDto fastEntryDto = null;
		for (Map.Entry<String, List<FastEntryVO>> entry : fastEntryMap.entrySet()) 
		{
			for (FastEntryVO fastEntry : fastEntryList) 
			{
				if (fastEntry.getFastEntryId().equals(entry.getKey())) 
				{
					fastEntryDto = new FastEntryDto();
					BeanUtils.copyProperties(fastEntry, fastEntryDto);
					fastEntryDto.setFastEntryList(entry.getValue());
					fastEntryDtoList.add(fastEntryDto);
					break;
				}
			}
		}
		return fastEntryDtoList;
	}


	private Map<String, List<FastEntryVO>> getFastEntryDtoMap(List<FastEntryVO> fastEntryList) {
		Map<String, List<FastEntryVO>> entryMap = new HashMap<String, List<FastEntryVO>>(1);
		List<FastEntryVO> secondEntryList = null;
		FastEntryVO entry = null;
		for (FastEntryVO fastEntry : fastEntryList) {
			if (fastEntry.getParentId().equals("-1")) {
				continue;
			}
			entry = new FastEntryVO();
			BeanUtils.copyProperties(fastEntry, entry);// 复制属性
			if (entryMap.containsKey(fastEntry.getParentId())) {
				secondEntryList = entryMap.get(fastEntry.getParentId());
				secondEntryList.add(entry);
			} else {
				secondEntryList = new ArrayList<FastEntryVO>(1);
				secondEntryList.add(entry);
				entryMap.put(fastEntry.getParentId(), secondEntryList);
			}
		}
		return entryMap;
	}

Map集合的基本方法

方法的使用

	public List<CheckAdvice> removePicExtra(List<CheckAdvice> picList,List<CheckAdvice> list) {
	List<CheckAdvice> newList= new ArrayList<CheckAdvice>();
        HashMap<String, String> hashMap = new HashMap<String, String>();
        for (CheckAdvice checkAdvice : picList) {
            if (checkAdvice == null) {
                continue;
            }
            String  adviceId = checkAdvice.getAdviceId();
            if (adviceId != null) {
                String value = hashMap.get(adviceId);
                if (StringUtil.isEmpty(value)) { //如果value是空的  说明取到的这个adviceId是第一次取到
                    hashMap.put(adviceId, adviceId);
                } else {
                    continue;
                }
            }   
        }
        
        for (CheckAdvice checkAdvice : list) {
            if (checkAdvice == null) {
                continue;
            }
            String  adviceId = checkAdvice.getAdviceId();
            if (adviceId != null) {
                String value = hashMap.get(adviceId);
                if (StringUtil.isEmpty(value)) { //如果value是空的  说明取到的这个adviceId是第一次取到
                    hashMap.put(adviceId, adviceId);
                    newList.add(checkAdvice); 
                } else {
                    continue;
                }
            }   
        }
        hashMap.clear();
        return newList;
	}

源码

HashMap的put操作。

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
        boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;  //如果没有初始化则初始化table
        if ((p = tab[i = (n - 1) & hash]) == null)
            //这里 (n-1)&hash 是根据hash值得到这个元素在数组中的位置(即下标)
            tab[i] = newNode(hash, key, value, null);
        //如果数组该位置上没有元素,就直接将该元素放到此数组中的该位置上
        else {
            Node<K,V> e; K k;
            //第一节节点hash值同,且key值与插入key相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                //属于红黑树处理冲突
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                /链表处理冲突
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        //新增节点后如果节点个数到达阈值,则将链表转换为红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //更新hash值和key值均相同的节点Value值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

HashMap的get操作。

final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //如果第一个节点是TreeNode,说明采用的是数组+红黑树结构处理冲突
    //遍历红黑树,得到节点值
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && 
                                                       key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/82711625