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
public class Abc {
int id;
bool isClickable;
Abc(int i, boolean isCl){
this.id = i;
this.isClickable = iCl;
}
}
Main.java
List<Abc> abc = new ArrayList<Abc>();
//add entries here
//now sort them
Collections.sort(abc, new Comparator<Abc>(){
@Override
public int compare(Abc abc1, Abc abc2){
boolean b1 = abc1.isClickable;
boolean b2 = abc2.isClickable;
if (b1 == !b2){
return 1;
}
if (!b1 == b2){
return -1;
}
return 0;
}
});
Order before sorting: true true true false false false false true false false
Order after sorting: false false true true true true false false false false
It is also possible that way.
I want the items with
true
value to appear first. My solution would be:Another way to go is:
Java 8:
In this case one of the easiest solutions is to convert booleans to integers, where
false
is0
andtrue
is1
. Then return the difference of the second one and the first one.So:
should do it.
why dont use something like this, its easier and java 8
output: true,true,true,false,false
reverseOrder is for order first true and after false, in other case falses goes first
output: false,false,true,true,true