Foreach loop in java for Dictionary

后端 未结 4 1109
死守一世寂寞
死守一世寂寞 2021-02-19 20:15

I want to go through every items in a dictionary in java. to clarify what I want to do, this is the C# code

Dictionary LableList = new Dict         


        
相关标签:
4条回答
  • 2021-02-19 20:27

    I'm assuming you have a Map<String, Label> which is the Java built-in dictionary structure. Java doesn't let you iterate directly over a Map (i.e. it doesn't implement Iterable) because it would be ambiguous what you're actually iterating over.

    It's just a matter of choosing to iterate through the keys, values or entries (both).

    e.g.

    Map<String, Label> map = new HashMap<String, Label>();
    //...
    
    for ( String key : map.keySet() ) {
    }
    
    for ( Label value : map.values() ) {
    }
    
    for ( Map.Entry<String, Label> entry : map.entrySet() ) {
        String key = entry.getKey();
        Label value = entry.getValue();
    }
    

    Your C# code seems to be the same as iterating over the entries (the last example).

    0 讨论(0)
  • 2021-02-19 20:29

    I was trying to add the contents of one HashMap (a) into another HashMap (b).

    I found it simple to iterate through HashMap a this way:

    a.forEach((k, v) -> b.put(k, v));
    

    You can manipulate my example to do what ever you want on the other side of "->".

    Note that this is a Lambda expression, and that you would have to use Java 1.8 (Java 8) or later for this to work. :-)

    0 讨论(0)
  • 2021-02-19 20:33

    java.util.Map is the Dictionary equvivalent and below is an example on how you can iterate through each entry

    for(Map.Entry<K, V> e : map.entrySet())
    {
        System.out.println(e.getKey()+": "+e.getValue());
    }
    
    0 讨论(0)
  • 2021-02-19 20:41

    Your best bet is to use this:

    for (String key : LableList.keys()) {
        Label value = LableList.get(key);
    
        // do what you wish with key and value here
    }
    

    In Java however, a better bet is to not use Dictionary as you would in .NET but to use one of the Map subclasses, e.g. HashMap. You can iterate through one of these like this:

    for (Entry<String, Label> e : myMap.entrySet()) {
        // Do what you wish with e.getKey() and e.getValue()
    }
    

    You are also advised against using Dictionary in the official javadoc.

    0 讨论(0)
提交回复
热议问题