How to for each the hashmap?

This question already has an answer here:

  • How to efficiently iterate over each entry in a 'Map'? 38 answers

  • 我知道我对那个人有点晚了,但我会分享我的工作,以防别人帮助别人:

    HashMap<String, HashMap> selects = new HashMap<String, HashMap>();
    
    for(Map.Entry<String, HashMap> entry : selects.entrySet()) {
        String key = entry.getKey();
        HashMap value = entry.getValue();
    
        // do what you have to do here
        // In your case, another loop.
    }
    

    Lambda Expression Java 8

    In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations( Stream operations ) that looks similar to iterators from Iterable Interface.

    Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.

    HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
    /*
     *     Logic to put the Key,Value pair in your HashMap hm
     */
    
    // Print the key value pair in one line.
    hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
    

    Here is an example where a Lambda Expression is used:

        HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
        Random rand = new Random(47);
        int i=0;
        while(i<5){
            i++;
            int key = rand.nextInt(20);
            int value = rand.nextInt(50);
            System.out.println("Inserting key: "+key+" Value: "+value);
            Integer imap =hm.put(key,value);
            if( imap == null){
                System.out.println("Inserted");
            }
            else{
                System.out.println("Replaced with "+imap);
            }               
        }
    
        hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
    
    Output:
    
    Inserting key: 18 Value: 5
    Inserted
    Inserting key: 13 Value: 11
    Inserted
    Inserting key: 1 Value: 29
    Inserted
    Inserting key: 8 Value: 0
    Inserted
    Inserting key: 2 Value: 7
    Inserted
    key: 1 value:29
    key: 18 value:5
    key: 2 value:7
    key: 8 value:0
    key: 13 value:11
    

    Also one can use Spliterator for the same.

    Spliterator sit = hm.entrySet().spliterator();
    

    UPDATE


    Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.


    Map.values()

    HashMap<String, HashMap<SomeInnerKeyType, String>> selects =
        new HashMap<String, HashMap<SomeInnerKeyType, String>>();
    
    ...
    
    for(HashMap<SomeInnerKeyType, String> h : selects.values())
    {
       ComboBox cb = new ComboBox();
       for(String s : h.values())
       {
          cb.items.add(s);
       }
    }
    
    链接地址: http://www.djcxy.com/p/18000.html

    上一篇: 如何在Spring控制器中获取地图中的所有请求参数?

    下一篇: 如何为每个哈希映射?