Sort an ArrayList by primitive boolean type

前端 未结 8 836
北恋
北恋 2020-12-09 16:08

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

相关标签:
8条回答
  • 2020-12-09 16:31

    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;
            }
        });
    
    0 讨论(0)
  • 2020-12-09 16:33

    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

    0 讨论(0)
  • 2020-12-09 16:34

    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

    0 讨论(0)
  • 2020-12-09 16:39

    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.

    0 讨论(0)
  • 2020-12-09 16:43

    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.

    0 讨论(0)
  • 2020-12-09 16:48

    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);
            }
        });
    
    0 讨论(0)
提交回复
热议问题