Two methods (sorted) and Map for Traversing map

Source: Internet
Author: User

Two methods (sorted) and Map for Traversing map

Initialize a map

12345 Map<String, String> map = new HashMap<String, String>();map.put("1", "hell");map.put("2", "hello");map.put("3", "hel");map.put("4", "hello");

1. The first method is widely used.

1234 Set<String> keySet = map.keySet();for (String key : keySet) {    System.out.println("key= " + key + " and value= " + map.get(key));}

2. The second method is recommended when the capacity is large.

12345 Set<Map.Entry<String,String>> entySet =  map.entrySet();for (Map.Entry<String, String> entry : entySet) {    System.out.println("key= " + entry.getKey() + " and value= "            + entry.getValue());}

The experiment found that the output order is messy. Sort the order.

1. sort by key value

First, write a sorting class.

1234567 private static class KeyComparator implements        Comparator<Map.Entry<String, String>> {    public int compare(Map.Entry<String, String> m,            Map.Entry<String, String> n) {        return m.getKey().compareTo(n.getKey());    }}

Put the data in the list.

123456789 List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();list.addAll(map.entrySet()); KeyComparator kc = new KeyComparator();Collections.sort(list, kc);for (Iterator<Map.Entry<String, String>> it = list.iterator(); it        .hasNext();) {    System.out.println(it.next());}

2. sort by Value

1234567 private static class ValueComparator implements        Comparator<Map.Entry<String, String>> {    public int compare(Map.Entry<String, String> m,            Map.Entry<String, String> n) {        return m.getValue().compareTo(n.getValue());    }}

Sort output

12345678 list.clear();list.addAll(map.entrySet());ValueComparator vc = new ValueComparator();Collections.sort(list, vc);for (Iterator<Map.Entry<String, String>> it = list.iterator();    it.hasNext();) {    System.out.println(it.next());}

 

Tips: if any error occurs, please point it out and I will modify it in time

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.