Summary of common methods in Java's HashMap traversing HashMap printing HashMap sorting according to the value of the HashMap


HashMap is a very useful tool in programming and is used very frequently, so this article briefly summarizes the common methods of hashmap

Iterating over a HashMap

Iter can be obtained through the entryset and then traversed one by one

Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}

It can also be traversed directly by a simple for loop

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " +
entry.getValue());
}

Print HashMap

public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}

Sorting based on the value of the HashMap

class ValueComparator implements Comparator<String> {
Map<String, Integer> base;
public ValueComparator(Map<String, Integer> base) {
this.base = base;
}
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
//add a lot of entries
countMap.put("a", 10);
countMap.put("b", 20);
ValueComparator vc = new ValueComparator(countMap);
TreeMap<String,Integer> sortedMap = new TreeMap<String,Integer>(vc);
sortedMap.putAll(countMap);
printMap(sortedMap);

This approach is the most voted on stackoverflow, borrowing from the treeMap constructor


Recommended>>
1、Collegestyle Aging Wisdom Health Island Putuo Health and Aging Service Development Forum to Build an Aging Ecosystem
2、Macaus Big Data Dream
3、Blue Alliance IT Outsourcing Experts Four Tips for Businesses to Build Private Cloud Storage
4、The secret to a good cloud is detailed product research
5、LeZhicom revamped officially online to create a more focused smart home smart hardware portal

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号