Sort an ArrayList by primitive boolean type

纵然是瞬间 提交于 2019-11-28 09:43:45

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);
        }
    });

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.

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

stud91

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;
        }
    });

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.

Java 8:

 Collections.sort(abc, (abc1, abc2) ->
                  Boolean.compare(abc2.isClickable(), abc1.isClickable()));

It is also possible that way.

myList.sort((a, b) -> Boolean.compare(a.isSn_Principal(), b.isSn_Principal()));

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!