Sort ArrayList of objects based on boolean value
in
Programming Questions
•
2 years ago
All right, suppose I have a class Photo with a lot of stuff in it. Including the boolean selected. Now I have a lot of these Photo's in an ArrayList. I would like to sort these photos based on the boolean selected. Where the true ones are sorted to the front of the list and the false ones are sorted to the end. I've looked into both "implements comparable" and creating a "custom comparator", but so far I've not been able to implement either into a workable solution. Below is a basic sketch which is comparable (no pun intended) to the actual sketch. Now I ask of you...
What would be the most efficient way to sort this ArrayList?
What would be the most efficient way to sort this ArrayList?
- ArrayList <Photo> photos = new ArrayList <Photo> ();
- void setup() {
- size(200,200);
- for (int i=0; i<10; i++) {
- float flipcoin = random(1);
- if (flipcoin>0.3) { photos.add(new Photo(i,false)); }
- else { photos.add(new Photo(i,true)); }
- }
- // sort ArrayList here on the boolean selected
- for (Photo p : photos) {
- println(p.selected + "," + p.index);
- }
- // sorted ArrayList with the true ones first and after that the false ones
- }
- class Photo {
- int index;
- boolean selected;
- int a,b,c,d;
- float e,f,g,h;
- PImage i,j,k;
- Photo(int index, boolean selected) {
- this.index = index;
- this.selected = selected;
- }
- }
1