[Java] ArrayList – sorting

Let’s say I am writing a program to keep track of amount of hours we spent on testing each engine, I need to utimately generate a report. It will be nice if I can sort the Engine based on it’s Serial number. So here’s the easy way to sort an ArrayList.

We sill use the method:

Collections.sort(list, comparator);

Main.java


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

public class Main {

    public static void main(String[] args)
    {
    //Create the ArrayList containing Engines of similar Prefix
    ArrayList engines = new ArrayList();

    //Add Engine Elements
    engines.add(new Engine("123-159"));
    engines.add(new Engine("123-555"));
    engines.add(new Engine("123-582"));
    engines.add(new Engine("123-668"));
    engines.add(new Engine("123-325"));
    engines.add(new Engine("123-458"));

    //Sort Engine  - Note Serial Data is stored in data[0]
     Comparator compare = new Comparator()
        {
            //Defining the How we Want to Sort the List
             public int compare(Object obj, Object obj2)
           {
               Engine engine1 = (Engine) obj;
               Engine engine2 = (Engine) obj2;
               return engine1.getData()[0].compareTo(engine2.getData()[0]);
           }
        };

        //The actual funtion to sort the list, take argument (List, Comparator)
        Collections.sort(engines, compare);

     //Print Out Engine List
     for(int i = 0; i < engines.size();  i++)
         System.out.println(engines.get(i).getData()[0]);

    }

}

Engine.java


public class Engine {

    private String serial;
    private double ptt;
    private double prod;
    private double loss;
    private double pts;

    public Engine(Engine e)
    {
        serial = e.serial;
        ptt = e.ptt;
        prod = e.prod;
        loss = e.loss;
        pts = e.pts;
    }

    public Engine(String _serial)
    {
        serial = _serial;
        ptt = 0;
        prod = 0;
        loss = 0;
        pts = 0;
    }

    public void setData(double _ptt, double _prod, double _loss, double _pts)
    {
        ptt += _ptt;
        prod += _prod;
        loss += _loss;
        pts += _pts;
    }

    public String[] getData()
    {
        String[] data = new String[5];
        data[0] = serial;
        data[1] = ptt+"";
        data[2] = prod+"";
        data[3] = loss+"";
        data[4] = pts+"";
        return data;
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s