0

I've been trying to find possible answers, but found none.

I've got an ArrayList full of custom objects. One of their fields is a boolean.

I want to put this object first, keeping the rest of elements

For instance, if I've got this list and obj5 is the one with this boolean set to true:

obj3, obj2, obj5, obj7, obj9

I'd like to get this:

obj5, obj3, obj2, obj7, obj9

EDIT: CAN'T USE LAMBDAS, JAVA 6

EDIT 2: PLEASE NOTE THAT THE REST OF THE LIST MUST KEEP THE OLD ORDER

EDIT 3: In short words, I need this program to output [B, A, C, D, E]:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Trip {

@Override
public String toString() {
    return name;
}

private String name;
private boolean freeCancellation;


public Trip(String name, boolean freeCancellation) {
    this.name = name;
    this.freeCancellation = freeCancellation;
}

static Comparator<Trip> myOrder = new Comparator<Trip>() {
    public int compare(Trip a, Trip b) {
        if (a.freeCancellation == b.freeCancellation) return 0;
        return a.freeCancellation ? -1 : 1;
    }
};

public static void main(String [] args){
    Trip t1 = new Trip("A", false);
    Trip t2 = new Trip("B", true);
    Trip t3 = new Trip("C", false);
    Trip t4 = new Trip("D", true);
    Trip t5 = new Trip("E", false);


    List<Trip> tripList = new ArrayList<>();
    tripList.add(t1);
    tripList.add(t2);
    tripList.add(t3);
    tripList.add(t4);
    tripList.add(t5);

    System.out.println(Arrays.toString(tripList.toArray()));
    Collections.sort(tripList, myOrder);
    //result should be [B, A, C, D, E]
    System.out.println(Arrays.toString(tripList.toArray()));
}

}
stack man
  • 2,303
  • 9
  • 34
  • 54

5 Answers5

6

Write a Comparator.

Comparator<MyType> myOrder = new Comparator<MyType>() {
    public int compare(MyType a, MyType b) {
         return (b.booleanField() ? 1 : 0) - (a.booleanField() ? 1 : 0);
    }
}

Sort using this comparator.

Collections.sort(myList, myOrder);

See Collections.sort

Edit

So it seems that what you're actually asking for is to move just one matching element to the front of your list. That ought to be pretty easy.

Find the index of the element you want to move:

int foundIndex = -1;
for (int i = 0; i < tripList.size(); ++i) {
    if (tripList.get(i).freeCancellation) {
        foundIndex = i;
        break;
    }
}

If you find such an element, and it is not already at the start, move it to the start:

if (foundIndex > 0) {
    tripList.add(0, tripList.remove(foundIndex));
}
Community
  • 1
  • 1
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Sorry but this is not mantaining order in the rest of the list – stack man Jan 19 '17 at 13:29
  • @stackman From the [documentation](https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)): "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort." – khelwood Jan 19 '17 at 13:33
  • I've updated the question so you can see what I am actually speaking about, thanks for your answer btw – stack man Jan 19 '17 at 13:38
0

Here is an example of how to achieve this:

class Element {
    public boolean shouldBeFirst();
}

List<Element> elements;
elements.sort(Comparator.comparing(Element::shouldBeFirst));

This works because the natural ordering of booleans is true first.

If you can't use Java 8 then the equivalent would be something like:

Collections.sort(elements, new Comparator() {
    int compareTo(Element el1, Element el2) {
        return (el1.shouldBeFirst() ? 1 : 0) - (el2.shouldBeFirst() ? 1 : 0);
    }
}
sprinter
  • 27,148
  • 6
  • 47
  • 78
0
 List<Object> objList = findObj(name);Collections.sort(objList, new Comparator<Object>() {
    @Override
    public int compare(Object a1, Object a2) {
        return (a1.getBooleanField()== a2.getBooleanField())?0:(a1.getBooleanField()?1:-1);
    }});

This might help you to resolve this. You modify the results by changing the compare logic

user4142018
  • 540
  • 1
  • 5
  • 12
0
import java.util.*;

public class Test {

    public static void main(String[] args) {
        List<A> list = new ArrayList<A>();
        list.add(new A(true));
        list.add(new A(false));
        list.add(new A(true));
        list.add(new A(false));
        Collections.sort(list);
        System.out.println(list);
    }

}

class A implements Comparable<A> {
    private boolean b;

    public A(boolean b) {
        this.b = b;
    }

    public boolean isB() {
        return b;
    }

    public void setB(boolean b) {
        this.b = b;
    }

    @Override
    public int compareTo(A a) {
        return a.isB() ? 1 : -1;
    }

    @Override
    public String toString() {
        return "A [b=" + b + "]";
    }



}

Maybe this is what you are looking for. This is solution if you want to give natural ordering to object, then implement Comparable and use Collections.sort - https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List). If you have various members inside class, then maybe go with Comparator implementation, that way you can achieve many ways of sorting your objects based on different members.

Avinash Anand
  • 655
  • 2
  • 15
  • 25
-1

If I understood what are you asking ,you need to create a new class called "Comparators". in this class you need to define your methods and they need to be static final ... then you can use it by calling to Collections.sort(-your array-, Comparator method name);