forEach

  1. public static void fashion(Map<String, String> map) {
  2. map.forEach((key, value) -> System.out.println("key = " + key + ", value = " + value));
  3. }

keySet + forEach

  1. public static void fashion(Map<String, String> map) {
  2. Set<String> keySet = map.keySet();
  3. keySet.forEach(key -> {
  4. System.out.println("key = " + key + ", value = " + map.get(key));
  5. });
  6. }

keySet + for 循环

  1. public static void fashion(Map<String, String> map) {
  2. Set<String> keySet = map.keySet();
  3. for (String key : keySet) {
  4. System.out.println("key = " + key + ", value = " + map.get(key));
  5. }
  6. }

keySet + iterator

  1. public static void fashion(Map<String, String> map) {
  2. Set<String> keySet = map.keySet();
  3. Iterator<String> iterator = keySet.iterator();
  4. while (iterator.hasNext()) {
  5. String next = iterator.next();
  6. System.out.println("key = " + next + ", value = " + map.get(next));
  7. }
  8. }

keySet + stream 流

  1. public static void fashion(Map<String, String> map) {
  2. map.keySet().stream().forEach(key -> {
  3. System.out.println("key = " + key + ", value = " + map.get(key));
  4. });
  5. }

entrySet + forEach

  1. public static void fashion5(Map<String, String> map) {
  2. Set<Map.Entry<String, String>> entrySet = map.entrySet();
  3. entrySet.forEach(entry -> {
  4. System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
  5. });
  6. }

entrySet + for 循环

  1. public static void fashion4(Map<String, String> map) {
  2. Set<Map.Entry<String, String>> entrySet = map.entrySet();
  3. for (Map.Entry<String, String> entry : entrySet) {
  4. System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
  5. }
  6. }

entrySet + iterator

  1. public static void fashion5(Map<String, String> map) {
  2. Set<Map.Entry<String, String>> entrySet = map.entrySet();
  3. Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
  4. while (iterator.hasNext()) {
  5. Map.Entry<String, String> next = iterator.next();
  6. System.out.println("key = " + next.getKey() + ", value = " + next.getValue());
  7. }
  8. }

entrySet + stream 流

  1. public static void fashion7(Map<String, String> map) {
  2. map.entrySet().stream().forEach(entry -> {
  3. System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
  4. });
  5. }

Map#values 只能拿到所有 value

  1. public static void fashion6(Map<String, String> map) {
  2. Collection<String> values = map.values();
  3. for (String value : values) {
  4. System.out.println("value = " + value);
  5. }
  6. }