I want to sort my ArrayList
using a boolean type. Basically i want to show entries with true
first. Here is my code below:
Abc.java
I want the items with true
value to appear first. My solution would be:
Collections.sort(m_mall, new Comparator<Mall>(){
@Override
public int compare(Mall mall1, Mall mall2){
boolean b1 = mall1.isClickable;
boolean b2 = mall2.isClickable;
return (b1 != b2) ? (b1) ? -1 : 1 : 0;
}
});
why dont use something like this, its easier and java 8
listOfABCElements = {true, false, false, true, true};
listOfABCElements.stream().sorted(Comparator.comparing(Abc::isClickable,Comparator.reverseOrder()).collect(Collectors.toList());
output: true,true,true,false,false
reverseOrder is for order first true and after false, in other case falses goes first
listOfABCElements.stream().sorted(Comparator.comparing(Abc::isClickable).collect(Collectors.toList());
output: false,false,true,true,true
Using Kotlin you can do smth like this:
listOfABCElements.sortBy { it.isClickable }
output: true,true,true,false,false
in reverse order:
listOfABCElements.sortByDescending { it.isClickable }
output: false,false,true,true,true
A simple suggestion would be to use the object Boolean
instead of boolean and use Collections.sort
.
However, you must know that the false
will be before the true
because true are represented as 1
and false as 0
. But then, you could just change your algorithm and access in reverse order.
Edit : As soulscheck stated, you could use Collections.reverseOrder
to revert the ordering imposed by the Comparator.
In this case one of the easiest solutions is to convert booleans to integers, where false
is 0
and true
is 1
. Then return the difference of the second one and the first one.
So:
int b1 = abc1.isClickable ? 1 : 0;
int b2 = abc2.isClickable ? 1 : 0;
return b2 - b1
should do it.
Another way to go is:
Collections.sort(abc, new Comparator<Abc>() {
@Override
public int compare(Abc abc1, Abc abc2) {
return Boolean.compare(abc2.isClickable,abc1.isClickable);
}
});