How To Perform Enhanced List Sorting with Comparator Interface

How To Perform Enhanced List Sorting with Comparator Interface

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

🚀 Get ready for the exciting new feature coming with Salesforce's Winter '24 release! In this blog post, I will dive deep into how this update is set to revolutionize the way you sort list elements within your Salesforce code.

📑 With the Winter '24 release, the List class receives a significant upgrade by introducing support for the all-new Comparator interface. This powerful enhancement empowers developers to implement a wide range of sorting orders effortlessly using the List.sort() method with a Comparator parameter.

💡 I will walk you through the ins and outs of using this feature, demonstrating its incredible versatility and practicality. Whether you need to sort lists of custom objects or standard data types, the Comparator interface offers a flexible solution for every sorting scenario.

If you prefer watching videos, you can watch my YouTube video covering these enhancements below.

Introduction

The List class now supports the new Comparator interface, so you can implement different sort orders in your code by using List.sort() with a Comparator parameter. To perform locale-sensitive comparisons and sorting, use the getInstance method in the new Collator class. Because locale-sensitive sorting can produce different results depending on the user running the code, avoid using it in triggers or in code that expects a particular sort order.

How

Implement the compare() method of the System.Comparator interface, and specify the Comparator as a parameter to List.sort(). Your implementation must explicitly handle null inputs in the compare() method to avoid a null pointer exception. This example implements two different ways of sorting employees.

Example 1 - Sorting Based On String Comparison

Here is the Student Class which has studentId, studentName and studentAge as member variables. Constructor of the class is instantiating the class and finally the two member functions getStudentName() and getStudentAge are returning student's name and age respectively.

 

public class Student {
 private Integer studentId;
 private String studentName;
 private Integer studentAge; 
 // Constructor
 public Student(Integer studentId, String studentName, Integer studentAge) {
 this.studentId = studentId;
 this.studentName = studentName;
 this.studentAge = studentAge;
 } 
 public String getStudentName() { return studentName; }
 public Integer getStudentAge() { return studentAge; }
}

Now consider a list containing the below students with their details. The question is how can we sort the list elements which is all the students based on their names?

List<Student> allStudents = new List<Student>();
allStudents.add(new Student(101,'Joe Smith', 14));
allStudents.add(new Student(102,'Shane Smith', 6));
allStudents.add(new Student(25,'Caragh Smith', 9));
allStudents.add(new Student(105,'Mario Ruiz', 11));

Now to sort the above list based on Student name, I can write my own Comparator class after Winter 24 Release. Inside the comparator class, I will be writing my own custom logic to perform the comparison between two list elements. Here is the custom comparator class.

public class StudentNameCompare implements Comparator<Student>{ 
 public Integer compare(Student s1, Student s2){
 if(s1?.getStudentName() == null && s2?.getStudentName() == null){
 return 0;
 }else if(s1?.getStudentName() == null){
 return -1;
 }else if(s2?.getStudentName() == null){
 return 1;
 }
 return s1.getStudentName().compareTo(s2.getStudentName());
 }
}

The important thing to remember is the Comparator interface. The class where the sorting/compare logic will be written should implement the Comparator interface. Then the compare function is the main section where the compare logic will be written.

With that, below is the test class to make sure lists are being sorted as per the logic writte.

@isTest
private class StudentCompareTest {
 @isTest static void testSortStudentByName() {
 List<Student> allStudents = new List<Student>();
 allStudents.add(new Student(101,'Joe Smith', 14));
 allStudents.add(new Student(102,'Shane Smith', 6));
 allStudents.add(new Student(25,'Caragh Smith', 9));
 allStudents.add(new Student(105,'Mario Ruiz', 11));
 StudentNameCompare studentNameCompare = new StudentNameCompare();
 allStudents.sort(studentNameCompare);
 Assert.areEqual('Caragh Smith', allStudents.get(0).getStudentName());
 Assert.areEqual('Joe Smith', allStudents.get(1).getStudentName());
 Assert.areEqual('Mario Ruiz', allStudents.get(2).getStudentName());
 Assert.areEqual('Shane Smith', allStudents.get(3).getStudentName());
 }
}

As you can see, the above test class is doing the assert based on the Student's name sorted alphabetically.

Example 2 - Sorting Based On Integer Comparison

For this example, I will use the same Student class and the same list of students, but this time list will be sorted based on Student Age.

Here is the comparator class where inside the compare function I have written the logic to compare two students based on their age.

public class StudentAgeCompare implements Comparator<Student>{
 public Integer compare(Student s1, Student s2){
 if(s1?.getStudentAge() == null && s2?.getStudentAge() == null){
 return 0;
 }else if(s1?.getStudentAge() == null){
 return -1;
 }else if(s2?.getStudentAge() == null){
 return 1;
 }else if(s1?.getStudentAge() > s2?.getStudentAge() ){
 return 1;
 }else if(s1?.getStudentAge() < s2?.getStudentAge() ){
 return -1;
 }else{
 return 0;
 }
 }
}

With the above comparator class, below is the test class to check whether the list is properly being sorted based on student's age.

@isTest
private class StudentCompareTest {
 @isTest static void testSortStudentByAge() {
 List<Student> allStudents = new List<Student>();
 allStudents.add(new Student(101,'Joe Smith', 14));
 allStudents.add(new Student(102,'Shane Smith', 6));
 allStudents.add(new Student(25,'Caragh Smith', 9));
 allStudents.add(new Student(105,'Mario Ruiz', 11));
 StudentAgeCompare studentAgeCompare = new StudentAgeCompare();
 allStudents.sort(studentAgeCompare);
 Assert.areEqual('Shane Smith', allStudents.get(0).getStudentName());
 Assert.areEqual('Caragh Smith', allStudents.get(1).getStudentName());
 Assert.areEqual('Mario Ruiz', allStudents.get(2).getStudentName());
 Assert.areEqual('Joe Smith', allStudents.get(3).getStudentName());
 }
}

As you can see, the above test class is doing the assert based on the Student's age sorted.

Example 3 - Use Of Collator Class To Sort Based On The User Locale

To perform locale-sensitive comparisons and sorting, use the getInstance method in the new Collator class. Because locale-sensitive sorting can produce different results depending on the user running the code, avoid using it in triggers or in code that expects a particular sort order.

Inside the below test class, I am doing sorting based on user locale (German).

@IsTest
private class SortGermanFoods {
 @isTest static void testSorting() {
 string userLocale = 'de_DE';
 User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
 EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
 LocaleSidKey=userLocale, TimeZoneSidKey='America/Los_Angeles',
 ProfileId = [SELECT Id FROM Profile WHERE Name='Standard User'].Id,
 UserName='standarduser' + DateTime.now().getTime() + '@testorg.com');
 System.runAs(u){
 List<String> foodName = new List<String> {
 'Käse',
 'Milch',
 'Öl',
 'Knödel',
 'Gemüse'
 };
 Collator myCollator = Collator.getInstance();
 foodName.sort(myCollator);
 Assert.areEqual('Gemüse', foodName[0]);
 Assert.areEqual('Käse', foodName[1]);
 Assert.areEqual('Knödel', foodName[2]);
 Assert.areEqual('Milch', foodName[3]);
 Assert.areEqual('Öl', foodName[4]); 
 }
 }
}

The important thing here is the Collector class. I am using the getInstance() method to get reference of the Collector class and then using that reference to do the sorting based on user's locale.

Conclusion

Whether you're a seasoned Salesforce developer or just getting started, this Winter '24 release feature is sure to streamline your development process and make list sorting a breeze. 

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

Unleashing The Power of AI: Salesforce and Tableau GPT

Unleashing The Power of AI: Salesforce and Tableau GPT

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

Tableau AI marks the evolution of Tableau into an advanced generation, offering a comprehensive suite of features that integrates trusted generative AI across the entire Tableau Platform. This enhancement aims to streamline and universalize the process of data analysis and the consumption of insights on a large scale. It elevates every analytics user by offering intelligent, tailored, and contextually relevant insights seamlessly integrated into their workflow, thus speeding up the discovery of insights and minimizing redundant tasks. Analysts are supported by intelligent recommendations and guided within the product, all while maintaining the utmost standards of data security and privacy.

Administrators can tailor trusted, ethical, and open GPT-powered experiences to meet specific business requirements with Tableau AI, ensuring a balance between innovation and security. Tableau Pulse, fueled by Tableau AI, redefines the data experience for business professionals, equipping every worker with intelligent, individualized, and context-rich insights right within their work processes.

The generative AI features of Tableau AI ensure that Tableau Pulse not only provides automated analytics in an easily understandable format but also proactively predicts and addresses the user's forthcoming questions. It goes a step further to propose inquiries the user may not have considered, transforming the interaction between individuals and their data. This shift facilitates a data-driven culture throughout the organization, where insights are not just accessible but are also intuitive and actionable for every member.

The Evolution of Tableau

Tableau has been at the forefront of visual analytics, helping organizations make sense of their data in an intuitive and interactive manner. The integration with GPT models will elevate Tableau's capabilities, enabling users to interact with their data in natural language, making complex analytics accessible to a broader audience.

Key Features of the Integration

  1. Natural Language Processing: Users can now ask questions in natural language to derive insights from their data. GPT’s advanced language understanding ensures accurate, relevant, and detailed answers, transforming the way businesses interact with data.

  2. Enhanced Data Visualization: With GPT's capability to understand and generate text, expect improvements in Tableau's already stellar data visualization. Automatically generated insights will accompany visualizations, making it easier for users to understand and interpret data.

  3. Automated Data Analysis: The combination of GPT and Tableau will enable automated data analysis. Users can receive instant insights without needing expertise in data science, making informed decision-making faster and more accessible.

  4. Customization and Flexibility: The integration will be customizable to cater to various industry-specific needs. Companies can tailor the AI to understand and respond according to their unique business contexts and terminologies.

Impact on Businesses

The integration of Tableau and GPT is anticipated to make a significant impact on businesses across the globe. It is not just a leap in the field of analytics but also a stride towards democratizing data. Organizations will be able to:

  1. Improve Decision Making: With enhanced AI-driven insights, companies can make informed decisions quickly, driving efficiency and competitiveness.

  2. Enhance Accessibility: The natural language interface will make data analytics accessible to non-technical users, promoting a data-driven culture across organizations.

  3. Drive Innovation: The combination of visual and linguistic analytics will spur innovation, opening new avenues for exploring and leveraging data.

Demo

You can watch the demo here.

Final Thoughts

Salesforce’s recent announcement marks the dawn of a new era in business intelligence. The integration of Tableau with GPT promises to unlock a world where data analytics is not just about visualizing data but conversing with it, understanding it, and drawing actionable insights in real-time. Organizations equipped with this revolutionary technology will be poised to navigate the complexities of the business landscape with unprecedented agility and intelligence.

Stay tuned as we continue to explore and unravel the myriad of possibilities that this integration is set to unleash in the corporate world, shaping the future of business intelligence and decision-making.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

Salesforce Winter 24 Release | Permission Related Enhancements

Salesforce Winter 24 Release | Permission Related Enhancements

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

Welcome to the Winter ’24 Release! Salesforce Release is the process by which Salesforce updates its software platform to add new features, enhancements, and bug fixes. Salesforce releases typically occur three times a year, in spring, summer, and winter, and are named after the season in which they are released. In this post, I am going to share all the new enhancements related to permissions that are coming along with Winter 24 release.

If you prefer watching videos, you can watch my YouTube video covering these enhancements below.

See What’s Enabled in a Permission Set More Easily (Beta)

Managing permissions within a permission set can sometimes be challenging. However, Salesforce made it more convenient to oversee users' access and permissions. You can now effortlessly view all active object, user, and field permissions on a single page, eliminating the need for numerous clicks. Furthermore, you can identify the permission set groups that include this particular permission set. 

When you open any permission set, you will find a new button named "View Summary (Beta)" at the top of the page.

Clicking on that button, and you will get the summary of Permission Set Groups this permission is being added to, User Permissions (App & System Permissions), Object Permissions and System Permissions.

Report on Custom Permission Set and Permission Set Group Assignments

To simplify user management, you can establish a custom report type and generate reports concerning custom permission sets and permission set group assignments. These reports enable you to:

1. Easily identify all users allocated to a particular custom permission set or permission set group.
2. Utilize the report to assess the assignments of an individual user.

This functionality empowers you to streamline your user management processes efficiently.

From Setup, in the Quick Find box, enter Report Types, and then select Report Types. Select Permission Set Assignment as the primary object. 

Select All Fields When Configuring Field Permissions

Within permission sets, you now have the capability to swiftly toggle Read or Edit access for all fields with a single click, rather than the time-consuming process of individually configuring each field's permission. This enhancement offers significant time savings, especially for tasks like configuring API-only integration users or transitioning profiles to permission sets.

However, it's crucial to maintain security best practices by enabling only the necessary field permissions that align with your users' specific business requirements.

Troubleshoot Permission Set Group Errors

To expedite issue resolution, the latest actionable error message linked to a permission set group is now prominently featured on its detailed page. Additionally, you have the ability to manually recalculate permission set groups, particularly when they encounter a failed status, following deployments or package updates. Previously, this required making updates to the permission set group, but now you can initiate recalculation directly when needed.

See API Names for Object and Field Permissions in Permission Sets

While configuring object and field permissions within permission sets, you'll notice a helpful enhancement. In addition to the object and field label, the Object API Name and Field API Name are now presented. This update simplifies the differentiation of objects and fields, which can be especially useful when dealing with multiple components that share the same name.

See How Many Permission Set Groups a Permission Set Is Added To

Now, you have the ability to view a count of how many permission set groups include a particular permission set. This count serves as a valuable tool to estimate the potential impact on your users before implementing any modifications to a permission set.

Automate and Migrate User Access with Improved User Access Policy Filters (Beta)

You now have the capability to reference a total of three permission sets, permission set groups, or managed package licenses within your user access policy filters. This enhancement makes it more convenient to pinpoint and target your intended users precisely. Previously, you were limited to referencing only one permission set, permission set group, or managed package license at a time.

With user access policies, you can automate user assignments to managed package licenses, permission sets, and other access mechanisms based on criteria that you define. These policies can run automatically during user creation or updates, or for streamlining user migrations to new access configurations in a single operation. It's worth noting that this feature remains available in beta during Winter '24.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments