杰瑞科技汇

Java中List与Map如何选择使用?

Of course! This is a very common and essential task in Java. Working with a List of Map objects (or vice-versa) is a fundamental pattern for handling structured data, especially when dealing with JSON APIs or database results.

Java中List与Map如何选择使用?-图1
(图片来源网络,侵删)

Let's break it down into several common scenarios with clear code examples.

Creating a List of Maps

This is the most basic operation. You often create this structure when you have multiple records, and each record is a collection of key-value pairs.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListOfMapsExample {
    public static void main(String[] args) {
        // 1. Create the List
        List<Map<String, Object>> userList = new ArrayList<>();
        // 2. Create the first Map (representing the first user)
        Map<String, Object> user1 = new HashMap<>();
        user1.put("id", 101);
        user1.put("name", "Alice");
        user1.put("active", true);
        user1.put("roles", List.of("Admin", "User")); // Can hold other collections
        // 3. Create the second Map
        Map<String, Object> user2 = new HashMap<>();
        user2.put("id", 102);
        user2.put("name", "Bob");
        user2.put("active", false);
        user2.put("roles", List.of("User"));
        // 4. Add the Maps to the List
        userList.add(user1);
        userList.add(user2);
        // 5. Print the result
        System.out.println(userList);
        // Output: [{id=101, name=Alice, active=true, roles=[Admin, User]}, {id=102, name=Bob, active=false, roles=[User]}]
    }
}

Explanation:

  • List<Map<String, Object>>: This is the type declaration. It means "a list where each element is a map. The map's keys are Strings and its values can be any Object type." Using Object is flexible but requires casting when you retrieve the values.
  • new ArrayList<>(): We create an instance of the ArrayList class to hold our maps.
  • new HashMap<>(): We create a HashMap for each user.
  • map.put(key, value): We add key-value pairs to each map.
  • list.add(map): We add each completed map to our list.

Iterating Over a List of Maps

This is the most common operation: you need to process each element (which is a map) in the list.

Java中List与Map如何选择使用?-图2
(图片来源网络,侵删)

Using a classic for loop (by index)

This is useful if you need the index for some reason.

for (int i = 0; i < userList.size(); i++) {
    Map<String, Object> currentUser = userList.get(i);
    System.out.println("Processing User #" + (i + 1));
    System.out.println("ID: " + currentUser.get("id"));
    System.out.println("Name: " + currentUser.get("name"));
    System.out.println("Status: " + (currentUser.get("active").equals(true) ? "Active" : "Inactive"));
    System.out.println("----------------------");
}

Using an enhanced for-each loop (Recommended)

This is cleaner and more readable for simply iterating through all elements.

for (Map<String, Object> userMap : userList) {
    System.out.println("Processing User: " + userMap.get("name"));
    System.out.println("ID: " + userMap.get("id"));
    System.out.println("Status: " + userMap.get("active"));
    System.out.println("----------------------");
}

Using Java 8 Streams (Modern & Powerful)

Streams are excellent for more complex operations like filtering, mapping, and collecting.

// Example 1: Print the name of every active user
userList.stream()
        .filter(user -> (boolean) user.get("active")) // Filter for active users
        .forEach(user -> System.out.println("Active User: " + user.get("name")));
// Example 2: Get a list of names of all users
List<String> names = userList.stream()
                             .map(user -> (String) user.get("name")) // Extract the 'name' value
                             .toList(); // Collect results into a new list
System.out.println("All User Names: " + names);

Accessing Data Inside the Maps

When you retrieve a value from the map, it's of type Object. You must cast it to the correct type to use it.

Java中List与Map如何选择使用?-图3
(图片来源网络,侵删)
Map<String, Object> firstUser = userList.get(0);
// Get a String value
String name = (String) firstUser.get("name");
System.out.println("Name (as String): " + name);
// Get an Integer value
int id = (Integer) firstUser.get("id"); // Autounboxing from Integer to int
System.out.println("ID (as int): " + id);
// Get a Boolean value
boolean isActive = (boolean) firstUser.get("active"); // Autounboxing from Boolean to boolean
System.out.println("Is Active (as boolean): " + isActive);
// Get a List value
List<String> roles = (List<String>) firstUser.get("roles");
System.out.println("Roles (as List): " + roles);

⚠️ Important Note on Generics: The raw type Map<String, Object> is flexible but not type-safe. A better approach is to define specific types for your values if you know them in advance.

// A more type-safe version
List<Map<String, String>> stringDataList = new ArrayList<>();
Map<String, String> item1 = new HashMap<>();
item1.put("product", "Laptop");
item1.put("category", "Electronics");
stringDataList.add(item1);
// Now you don't need to cast when getting values
String product = stringDataList.get(0).get("product"); // No cast needed!

Common Operations

Finding a Map in a List by a Key's Value

Let's find the user with the name "Bob".

String nameToFind = "Bob";
for (Map<String, Object> user : userList) {
    if (nameToFind.equals(user.get("name"))) {
        System.out.println("Found user: " + user);
        break; // Found it, no need to continue
    }
}

Modifying a Map Inside the List

Let's change Bob's status to active.

for (Map<String, Object> user : userList) {
    if ("Bob".equals(user.get("name"))) {
        user.put("active", true); // Modify the value in the map
        System.out.println("Updated Bob's status to: " + user.get("active"));
        break;
    }
}
System.out.println(userList);

Adding a New Key-Value Pair to a Map

Let's add an "email" field to Alice.

for (Map<String, Object> user : userList) {
    if ("Alice".equals(user.get("name"))) {
        user.put("email", "alice@example.com");
        break;
    }
}
System.out.println(userList);

The Reverse: A Map of Lists

Sometimes you have a list of objects and you want to group them by a common property into a map. For example, group users by their active status.

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class MapOfListsExample {
    public static void main(String[] args) {
        List<Map<String, Object>> userList = List.of(
            Map.of("id", 101, "name", "Alice", "active", true),
            Map.of("id", 102, "name", "Bob", "active", false),
            Map.of("id", 103, "name", "Charlie", "active", true)
        );
        // Group users by their 'active' status
        Map<Boolean, List<Map<String, Object>>> usersByStatus = userList.stream()
            .collect(Collectors.groupingBy(user -> (boolean) user.get("active")));
        System.out.println(usersByStatus);
        /*
        Output:
        {
          false=[{id=102, name=Bob, active=false}],
          true=[{id=101, name=Alice, active=true}, {id=103, name=Charlie, active=true}]
        }
        */
    }
}

Summary

Task Key Concept / Code Snippet
Create a List of Maps List<Map<String, Object>> list = new ArrayList<>(); list.add(new HashMap<>());
Iterate with a for-each loop for (Map<String, Object> map : list) { ... }
Iterate with Java 8 Streams list.stream().forEach(map -> { ... });
Access a value from a map Object value = map.get("key"); (Requires casting)
Find an item in the list Use a for-each loop with an if condition to check a key's value.
Modify an item in the list Find the map in the list and then call map.put("newKey", newValue); on it.
Group a list into a map (Java 8) Map<K, List<T>> result = list.stream().collect(Collectors.groupingBy(item -> item.getKeyToGroupBy()));
分享:
扫描分享到社交APP
上一篇
下一篇