[Simple Java] commonly used HashMap method, simplejavahashmap

Source: Internet
Author: User

[Simple Java] commonly used HashMap method, simplejavahashmap

HashMap is very useful when you need to count elements. For example, count the number of times each character appears in a string:

package simplejava;import java.util.HashMap;import java.util.Map.Entry;public class Q12 {    public static void main(String[] args) {        HashMap<Integer, Integer> countMap = new HashMap<Integer, Integer>();        // .... a lot of a’s like the following                String chars = "abcabcabcghgk";                for(int i = 0; i < chars.length(); i++){            int a = chars.charAt(i);            if (countMap.keySet().contains(a)) {                countMap.put(a, countMap.get(a) + 1);            } else {                countMap.put(a, 1);            }        }                        for(Entry<Integer, Integer> e : countMap.entrySet()){            System.out.println((char)(int)e.getKey() + " " + e.getValue());        }    }}

Output result:

G 2
B 3
C 3
A 3
K 1
H1hashmap Traversal
        Map<Integer, Integer> mp = new HashMap<Integer, Integer>();        Iterator it = mp.entrySet().iterator();        while (it.hasNext()) {            Map.Entry pairs = (Map.Entry) it.next();            System.out.println(pairs.getKey() + " = " + pairs.getValue());        }                        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 Elements
    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        }    }
Sort by values of key-value pairs

The following code transfers a comparator to the TreeMap constructor to sort the map:

package simplejava;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.TreeMap;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    }}public class Q12 {    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        }    }    public static void main(String[] args) {        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);    }}

Although there are many ways to sort HashMap, the above method is the most respected in stackoverflow;

Note: A Comparator is used to sort the TreeMap. The comparison key is used to retrieve the value corresponding to the key and compare the size;

 

Http://www.programcreek.com/2013/04/frequently-used-methods-of-java-hashmap/.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.