Java Map 常用的遍历方式

Java Map 的遍历方式主要有以下几种:

  1. 遍历所有的键(Key):
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        for (String key : map.keySet()) {
            System.out.println("Key: " + key);
        }
    }
}
  1. 遍历所有的值(Value):
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        for (Integer value : map.values()) {
            System.out.println("Value: " + value);
        }
    }
}
  1. 遍历所有的键值对(Entry):
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
  1. 使用Java 8的forEach()方法:
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
    }
}
  1. 使用Java 8的Stream API:
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);

        map.entrySet().stream()
                .forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
    }
}

以上是Java Map遍历的五种常见方法,可以根据实际需求选择合适的遍历方式。

你可能感兴趣的:(Java,java,开发语言)