Home  >  Article  >  Java  >  What are the methods of traversing Map in Java?

What are the methods of traversing Map in Java?

PHPz
PHPzforward
2023-05-06 20:40:061621browse

1. Create an Enum

public enum FactoryStatus {
    BAD(0,"ou"),
    GOOD(1,"yeah");

    private int status;
    private String description;
    FactoryStatus(int status, String description){
        this.status=status;
        this.description=description;
    }

    public int getStatus() {
        return status;
    }

    public String getDescription(){
        return description;
    }
}

This Enum is used as the value of the Map.

2. Start traversing

Method 1

Set set = map.keySet();
for (Object o : set) {
    System.out.println(o+""+map.get(o));
}

Traverse through the key set collection, and then use the key to get the value of the map. This method is more commonly used.

Method 2

Set set = map.keySet();
Iterator iterator = set.iterator();
while (iterator.hasNext()){
    Object next = iterator.next();
    System.out.println("key为:"+next+",value为:"+map.get(next));
}

Traverse the key set collection in the form of an iterator, and then use the key to get the value of the map.

Method 3

Set<Map.Entry<String, FactoryStatus>> entries = map.entrySet();
Iterator<Map.Entry<String, FactoryStatus>> iterator1 = entries.iterator();
while (iterator1.hasNext()){
    Map.Entry<String, FactoryStatus> next = iterator1.next();
    System.out.println("方法三的key为:"+next.getKey()+",value为:"+next.getValue());
}

Traverse the key-value pairs of the Map in the form of an iterator, and then obtain the values ​​of k and v through the .getKey() and .getValue() methods.

Method 4

Collection<FactoryStatus> values = map.values();
for (FactoryStatus value : values) {
    System.out.println("方法四的value为:"+value);
}

This method directly takes out the value of the map and puts it in the collection, and then loops through v.

Method 5

Set<Map.Entry<String, FactoryStatus>> entries = map.entrySet();
for (Map.Entry<String, FactoryStatus> entry : entries) {
    System.out.println("方法五的key为:"+entry.getKey()+",value为:"+entry.getValue());
}

Obtain all key-value pairs through the foreach loop and traverse all k and v. This method is theoretically recommended, especially when the capacity is large.

The above is the detailed content of What are the methods of traversing Map in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete