You can use Java's FastJSON library to efficiently group JSONArray data based on a specific value, creating a map with JSONArray keys and List values. This method enables structured organization of your data, making it easier to access and analyze. Below is an example code demonstrating this process:

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Example data
        JSONArray jsonArray = JSONArray.parseArray("[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":1,"name":"Charlie"}]");
        
        // Grouping field
        String groupBy = "id";
        
        // Create a Map to store grouped data
        Map<JSONArray, List<JSONArray>> groupedData = new HashMap<>();
        
        // Iterate through JSONArray
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            
            // Get the grouping value based on the grouping field
            JSONArray groupKey = new JSONArray();
            groupKey.add(jsonObject.get(groupBy));
            
            // If the grouping value already exists in the Map, add the data to the corresponding List
            if (groupedData.containsKey(groupKey)) {
                groupedData.get(groupKey).add(jsonObject);
            } else {
                // If the grouping value doesn't exist in the Map, create a new List and add the data to the List
                List<JSONArray> groupData = new ArrayList<>();
                groupData.add(jsonObject);
                groupedData.put(groupKey, groupData);
            }
        }
        
        // Print the grouped results
        for (Map.Entry<JSONArray, List<JSONArray>> entry : groupedData.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

Running the above code will output the following results:

Key: [1], Value: [{"id":1,"name":"Alice"},{"id":1,"name":"Charlie"}]
Key: [2], Value: [{"id":2,"name":"Bob"}]

In this example, we use a Map to store the grouped data, where the key is a JSONArray and the value is a List. While iterating through the JSONArray, we extract the value of the grouping field to create the grouping key and add the data to the corresponding List. Finally, we iterate through the Map and print the grouped results.

Java FastJSON: Group JSONArray by Value - Efficient Data Organization

原文地址: https://www.cveoy.top/t/topic/pv2p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录