Sort an ArrayList by primitive boolean type

2019-01-18 20:44发布

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

7条回答
Ridiculous、
2楼-- · 2019-01-18 20:45

It is also possible that way.

myList.sort((a, b) -> Boolean.compare(a.isSn_Principal(), b.isSn_Principal()));
查看更多
虎瘦雄心在
3楼-- · 2019-01-18 20:48

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;
        }
    });
查看更多
一夜七次
4楼-- · 2019-01-18 20:52

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);
        }
    });
查看更多
放荡不羁爱自由
5楼-- · 2019-01-18 20:55

Java 8:

 Collections.sort(abc, (abc1, abc2) ->
                  Boolean.compare(abc2.isClickable(), abc1.isClickable()));
查看更多
Luminary・发光体
6楼-- · 2019-01-18 20:55

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.

查看更多
萌系小妹纸
7楼-- · 2019-01-18 20:59

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

查看更多
登录 后发表回答