I'm trying to sort a List of Map object which looks something like this.
"list" : [
{
"up" : false,
more fields ....
},
{
"randomField" : "ABC",
"someMoreRandomField" : "Retirement"
more fields ....
},
{
"up" : false,
more fields ....
},
{
"last" : true,
"up" : false
more fields ....
},
{
"last" : true,
"up" : true
more fields ....
},
{
"up" : true
more fields ....
},
{
"up" : true
more fields ....
},
{
"up" : true
more fields ....
}
]
I want them to be sorted in based on these conditions. If Object has the key 'last' marked as true then they should be last in the list. If the key 'up' is true, they will appear first in the list. If the key 'last' marked as true will take precedence and should appear bottom of the list even if the same object has 'up' marked as true.
Sorted list:
"list" : [
{
"up" : true
more fields ....
},
{
"up" : true
more fields ....
},
{
"up" : true
more fields ....
},
{
"up" : false,
more fields ....
},
{
"randomField" : "ABC",
"someMoreRandomField" : "Retirement"
more fields ....
},
{
"up" : false,
more fields ....
},
{
"last" : true,
"up" : false
more fields ....
},
{
"last" : true,
"up" : true
more fields ....
}
]
I was able to achieve this using Vanilla JS, trying to the do the same in Java 8. Have been at it for quite some time, stumbled upon few answers: https://stackoverflow.com/a/46717991/2114024
But haven't found the solution yet.
JS code snippet:
list.sort(function(a,b) {
if(a.last === undefined) {a.last = false};
if(b.last === undefined) {b.last = false};
if(a.up === undefined) {a.up = false};
if(b.up === undefined) {b.up = false};
return Number(a.last) - Number(b.last) || Number(b.up) - Number(a.up);
});
Any suggestions are appreciated.