mport com.google.gson.Gson; import com.google.gson.JsonObject; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.*; public class FindDuplicateIdsInJsonFiles { public static void main(String[] args) { // Replace with the folder path containing JSON files String folderPath = "/path/to/json/files/folder"; File folder = new File(folderPath); // Call the method to find duplicate IDs List duplicates = findDuplicateIds(folder); // Output the duplicate records if (duplicates.isEmpty()) { System.out.println("No duplicate IDs found."); } else { System.out.println("Duplicate IDs found:"); System.out.printf("%-10s %-20s %-30s%n", "ID", "Value", "File Name"); System.out.println("------------------------------------------------------------"); for (DuplicateRecord record : duplicates) { System.out.printf("%-10s %-20s %-30s%n", record.getId(), record.getValue(), record.getFileName()); } } } public static List findDuplicateIds(File folder) { Map<String, List> idRecordsMap = new HashMap<>(); List duplicateRecords = new ArrayList<>(); // Check if the folder exists and contains files if (!folder.exists() || !folder.isDirectory()) { System.out.println("Invalid folder path!"); return duplicateRecords; } // Iterate over all JSON files in the folder File[] files = folder.listFiles((dir, name) -> name.endsWith(".json")); if (files == null || files.length == 0) { System.out.println("No JSON files found in the folder!"); return duplicateRecords; } Gson gson = new Gson(); for (File file : files) { try (FileReader reader = new FileReader(file)) { // Parse JSON file JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); // Extract the "id" field if (jsonObject.has("id")) { String id = jsonObject.get("id").getAsString(); String value = jsonObject.toString(); // Add the record to the map DuplicateRecord record = new DuplicateRecord(id, value, file.getName()); idRecordsMap.putIfAbsent(id, new ArrayList<>()); idRecordsMap.get(id).add(record); } } catch (IOException e) { System.err.println("Error reading file: " + file.getName()); e.printStackTrace(); } catch (Exception e) { System.err.println("Error parsing file: " + file.getName()); e.printStackTrace(); } } // Collect duplicate records for (Map.Entry<String, List> entry : idRecordsMap.entrySet()) { if (entry.getValue().size() > 1) { duplicateRecords.addAll(entry.getValue()); } } return duplicateRecords; } } // Class to represent duplicate records class DuplicateRecord { private final String id; private final String value; private final String fileName; public DuplicateRecord(String id, String value, String fileName) { this.id = id; this.value = value; this.fileName = fileName; } public String getId() { return id; } public String getValue() { return value; } public String getFileName() { return fileName; } }