DEV Community

Query Filter
Query Filter

Posted on

bridge-16

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

/**
 * Merges a list of local classes with external classes loaded from a target file.
 * Eliminates duplicates and returns a sorted list. Safely handles null, empty, 
 * or missing inputs.
 *
 * @param localClasses List of auto-discovered local class names (can be null or empty)
 * @param targetFilePath Path to the file containing external class targets (can be null or empty)
 * @return A unique, sorted List of class names (never null, but can be empty)
 */
public static List<String> mergeAndSortTargets(List<String> localClasses, String targetFilePath) {
    // TreeSet automatically eliminates duplicates and guarantees ascending alphabetical order
    Set<String> uniqueSortedClasses = new TreeSet<>();

    // 1. Process local classes if provided
    if (localClasses != null) {
        for (String className : localClasses) {
            if (className != null && !className.trim().isEmpty()) {
                uniqueSortedClasses.add(className.trim());
            }
        }
    }

    // 2. Process external classes from the target file path if provided
    if (targetFilePath != null && !targetFilePath.trim().isEmpty()) {
        File targetFile = new File(targetFilePath.trim());

        if (targetFile.exists() && targetFile.isFile()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(targetFile))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // Clean up whitespace and skip comments (#) or empty lines
                    String cleanLine = line.trim();
                    if (!cleanLine.isEmpty() && !cleanLine.startsWith("#")) {
                        uniqueSortedClasses.add(cleanLine);
                    }
                }
            } catch (Exception e) {
                System.err.println("[PROFILER-AGENT] Warning: Failed to read external target file: " + e.getMessage());
            }
        } else {
            System.out.println("[PROFILER-AGENT] Notice: External target file does not exist or is invalid: " + targetFilePath);
        }
    }

    // 3. Return as a standard List wrapper (guaranteed non-null, matches your sorting constraint)
    return new ArrayList<>(uniqueSortedClasses);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)