function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Bhupinder Walia 10Bhupinder Walia 10 

Sort object in Apex class

How we can sort below in Apex by color value.

[
{"text":"LETTER SENT","color":"RED"},
{"text":"ASSIGNED","color":"YELLOW"},
{"text":"LOAN","color":"GREEN"},
{"text":"MITIGATION","color":"RED"},
{"text":"PENDING ","color":"YELLOW"},
{"text":"RHI","color":"GREEN"},
{"text":"CIT","color":"YELLOW"}
]
SubratSubrat (Salesforce Developers) 
Hello Bhupinder ,

To sort the above list by color value in Apex, you can use the sort method of the List class.

Here's an example implementation:
List<String> jsonData = new List<String>{
    '{"text":"LETTER SENT","color":"RED"}',
    '{"text":"ASSIGNED","color":"YELLOW"}',
    '{"text":"LOAN","color":"GREEN"}',
    '{"text":"MITIGATION","color":"RED"}',
    '{"text":"PENDING ","color":"YELLOW"}',
    '{"text":"RHI","color":"GREEN"}',
    '{"text":"CIT","color":"YELLOW"}'
};

List<Map<String, Object>> dataList = new List<Map<String, Object>>();
for (String data : jsonData) {
    dataList.add((Map<String, Object>) JSON.deserializeUntyped(data));
}

dataList.sort((a, b) -> ((String)a.get('color')).compareTo((String)b.get('color')));

System.debug(dataList);

if it helps , please mark this as Best Answer.
Thank you.
 
ayesha javedayesha javed
To sort the given list of objects in Apex by color value, you can use the sort() method provided by the List class in Apex. Here's an example code snippet:
List<Object> myList = new List<Object>{
    new Map<String, Object>{'text' => 'LETTER SENT', 'color' => 'RED'},
    new Map<String, Object>{'text' => 'ASSIGNED', 'color' => 'YELLOW'},
    new Map<String, Object>{'text' => 'LOAN', 'color' => 'GREEN'},
    new Map<String, Object>{'text' => 'MITIGATION', 'color' => 'RED'},
    new Map<String, Object>{'text' => 'PENDING', 'color' => 'YELLOW'},
    new Map<String, Object>{'text' => 'RHI', 'color' => 'GREEN'},
    new Map<String, Object>{'text' => 'CIT', 'color' => 'YELLOW'}
};

// Sort the list by color value
myList.sort((a,b) => ((String)a.get('color')).compareTo((String)b.get('color')));

// Print the sorted list
System.debug(myList);
This code creates a list of objects containing maps with 'text' and 'color' keys. The sort() method is then called on the list with a lambda function as a parameter that compares the 'color' values of the two maps being compared. The result is a sorted list based on the 'color' values. The sorted list is then printed to the debug logs using the System.debug() method.