Without having business logic for any application, is good for nothing. And to handle business logic you definitely need to handle the different states of an object or array of objects. You might need to sort, filter get min, max or unique value from an array of objects.
In this blog, I am going to discuss on few real-life array handling scenario, such as -
- Sorting an array based on a particular object property value (Ascending & Descending)
- Filtering objects from two different array
- Find Min & Max value from an array
Every application needs to fulfill its business logic, and for that, it needs to manipulate or compute collections of data for representation. To handle data properly, we need to depend on different data structures like Array, Stack, Queue, Linked List, Doubly Linked List, Circular Linked List, Circular Queue, and so on. But the underneath of the main data structure is an Array.
Here, I am going to experiment with different scenarios with different collections of data to sort, compare, min value, max value, and whatnot.
How to sort (Ascending Or Descending) an array based on created date or any other specific Object property
Let's say, we have a multiple Account object in Account collection, like below -
So, to sort the collection, you can use the following code snippets to get actual results in ascending or descending order -
Consider a scenario, when you have master accounts and child accounts. Now you want to differentiate only those accounts which are present in the master data set.
|Master Data set||Child Data set|
To filter out only those specific objects from the master array, the following code needs to be executed.
The same if you want to filter elements that are only present in the child array, you need to interchange the inner array to upper and upper array to inner array. Like below -
Filter object from a collection based on Minimum & Maximum value
Consider you have a list of objects (i.e. List of account object) and now you wanted to filter only such object which is having a minimum balance in the account.
To find out the minimum & maximum value from the account collection, use the following code snippets -
How to Get Unique Elements from an Array of Objects
To get unique Array elements only, you can use Set to filter out objects. Here how I am getting it.
Please share your comments below and let me know if you are facing any different types of challenges using an array.