简体   繁体   English

Java HashMap就像ArrayList一样放入了增强的for循环

[英]Java HashMap put in an enhanced for loop just like an ArrayList

For example, I can loop an ArrayList like this 例如,我可以像这样循环一个ArrayList

for (String temp : arraylist)

Can I loop a HashMap by using the similar method? 我可以使用类似的方法循环HashMap吗?

You can iterate over the keys, entries or values. 您可以迭代键,条目或值。

for (String key : map.keySet()) {
    String value = map.get(key);
}

for (String value : map.values()) {
}

for (Map.Entry<String,String> entry : map.entrySet()) {
    String key = entry.getKey();
    String value = entry.getValue();
}

This is assuming your map has String keys and String values. 这假设您的地图具有字符串键和字符串值。

You can't directly loop a Map like that in Java. 你不能像Java那样直接循环Map

You can, however, loop the keys: 但是,您可以循环键:

for (SomeKeyObject key : map.keySet())

The values: 价值:

for (SomeValueObject value : map.values())

Or even its entries: 甚至是它的条目:

for (Map.Entry<SomeKeyObject, SomeValueObject> entry : map.entrySet())

you can do 你可以做

for (String key : hashmap.keySet()) {
    String value = hashmap.get(key);
}

You can do it by using an Iterator http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html . 您可以使用Iterator http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html来完成此操作。

    HashMap<String, String> yourHashMap = new HashMap<>();
    Iterator<Map.Entry<String, String>> it = yourHashMap.entrySet().iterator();
    while(it.hasNext()){
        it.next();
        System.out.println(yourHashMap.get(it));
    }

At first sight it might be tempting to use a for-loop instead of an Iterator, but 乍一看,使用for-loop而不是Iterator可能很诱人,但是

you will need an Iterator if you want to modify the elements in your HashMap while iterating over them! 如果你想在迭代它们的同时修改HashMap中的元素,你将需要一个迭代器!

When using a for-loop you cannot remove elements from your map while 使用for循环时,无法从地图中删除元素

 it.remove()

would work well in the above example. 在上面的例子中会很好用。

public class IterableHashMap<T,U> extends HashMap implements Iterable
    {

        @Override
        public Iterator iterator() {
            // TODO Auto-generated method stub

            return this.keySet().iterator();
        }



    }



    public static void main(String[] args) {

        testA a=new testA();
        IterableHashMap test=a.new IterableHashMap<Object,Object>();
        for(Object o:test)
        {

        }
    }

用这个

map.forEach((k, v) -> System.out.printf("%s %s%n", k, v));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM