Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

java - Sort an ArrayList by primitive boolean type

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...