rawData
rawData

Reputation: 799

How to sort ArrayList of classes

I am trying to sort arrayList of classes which have a abstract type.

Here is my interface

public interface iSomeInterface {
    public int level();
}

There are couple of implementation of this interface which is different by their level implementations.

public class LevelOne implements iSomeInterface {
    @Override
    public int level() {return 1;}
}

public class LevelTwo implements iSomeInterface {
    @Override
    public int level() {return 2;}
}
public class LevelThree implements iSomeInterface {
    @Override
    public int level() {return 3;}
}

if I have couple of instances of these classes and passing them to the Levels class

ArrayList<iSomeInterface> someInterfaces = new ArrayList<iSomeInterface>();
        someInterfaces.add(new LevelOne());
        someInterfaces.add(new LevelTwo());
        someInterfaces.add(new LevelOne());
        someInterfaces.add(new LevelThree());
        someInterfaces.add(new LevelOne());
        Levels levels = new Levels(someInterfaces);

How can I sort these classed based on their level value.

public class Levels {
    private ArrayList<iSomeInterface> someInterfaces;

    public Levels(ArrayList<iSomeInterface> someInterfaces){

        this.someInterfaces = someInterfaces;
    }

    public ArrayList<iSomeInterface> sorting(){

        //some code to sorting instances

        return someInterfaces;
    }
}

Answer : Thanks for your helps, The final answer :

public class someComparator implements Comparator<iSomeInterface> {
 @Override
  public int compare(iSomeInterface first, iSomeInterface second) {
    return first.level()<second.level()?-1:first.level()==second.level()?0:1;
  }
}

public ArrayList<iSomeInterface> sorting(){
  Collections.sort(someInterfaces,new someComparator());
  return someInterfaces;
}

Upvotes: 0

Views: 196

Answers (1)

arosenber
arosenber

Reputation: 126

The simplest solution if you're using java 8.

public ArrayList<iSomeInterface> sorting(){

    Collections.sort(someInterfaces, (iSomeInterface  i1, iSomeInterface  i2) -> i1.getLevel() - i2.getLevel());

    return someInterfaces;
}

If you're working in something prior to that you can implement your own comparator...with an anonymous inner class to still make a 1-liner...

public ArrayList<iSomeInterface> sorting(){
    Collections.sort(interfaces, new Comparator<iSomeInterface>() {
        @Override
        public int compare(iSomeInterface i1, iSomeInterface i2) {
            return i1.getLevel() - i2.getLevel();
        }
    });
    return interfaces;
}

I assume you want to modify your member variable, but you can always duplicate your list first.

(Note Collections is java.util.Collections)

Upvotes: 2

Related Questions