1. import java.util.*;
  2. class ConfigRecord {
  3. String key;
  4. String value;
  5. public ConfigRecord(String key, String value) {
  6. this.key = key;
  7. this.value = value;
  8. }
  9. @Override
  10. public String toString() {
  11. return "Key: " + key + ", Value: " + value;
  12. }
  13. }
  14. public class MemoryEfficientConfigSorter {
  15. public static List<ConfigRecord> sortConfigRecords(List<ConfigRecord> records) {
  16. if (records == null || records.isEmpty()) {
  17. return new ArrayList<>(); // Return empty list for null or empty input
  18. }
  19. // Use a simple insertion sort for memory efficiency.
  20. // Insertion sort is good for small datasets and nearly sorted data.
  21. List<ConfigRecord> sortedRecords = new ArrayList<>(records); // Create a copy to avoid modifying the original
  22. for (int i = 1; i < sortedRecords.size(); i++) {
  23. ConfigRecord current = sortedRecords.get(i);
  24. int j = i - 1;
  25. // Move elements of sortedRecords[0..i-1], that are greater than current,
  26. // to one position ahead of their current position
  27. while (j >= 0 && sortedRecords.get(j).key.compareTo(current.key) > 0) {
  28. sortedRecords.set(j + 1, sortedRecords.get(j));
  29. j--;
  30. }
  31. sortedRecords.set(j + 1, current);
  32. }
  33. return sortedRecords;
  34. }
  35. public static void main(String[] args) {
  36. List<ConfigRecord> configRecords = new ArrayList<>();
  37. configRecords.add(new ConfigRecord("setting3", "value3"));
  38. configRecords.add(new ConfigRecord("setting1", "value1"));
  39. configRecords.add(new ConfigRecord("setting2", "value2"));
  40. configRecords.add(new ConfigRecord("setting4", "value4"));
  41. List<ConfigRecord> sortedConfigRecords = sortConfigRecords(configRecords);
  42. for (ConfigRecord record : sortedConfigRecords) {
  43. System.out.println(record);
  44. }
  45. }
  46. }

Add your comment