Data AccessCore JavaApp FrameworksViewTestingBuildingDeploymentDev ToolsSecurityOpinions

Wednesday, March 4, 2009

Sorting java.util.List with a java.util.Comparator using java.util.Collections

Sorting objects in a List is a piece of code that every java programmer will write more than once in their lifetime. Any object that implements the java.util.List interface can utilize the sort method contained within the java.util.Collections class to sort the list, using a java.util.Comparator.

Below is a short tutorial and code sample.

First, let's define our object model.

package com.company.model;

public class MilkDelivery {

private int daysTilExpiration;

public MilkDelivery(int daysTilExpiration){ 
this.daysTilExpiration = daysTilExpiration; 
}

public int getDaysTilExpiration() { 
return daysTilExpiration; 
}

public void setDaysTilExpiration(int daysTilExpiration) { 
this.daysTilExpiration = daysTilExpiration; }
}


Second, let's write a Comparator and implement the compare method.

package com.company.model.comparator;

import java.util.Comparator;

import com.company.model.MilkDelivery;

public class MilkDeliveryComparator implements Comparator {

/** Supports sorting from days til expiration ascending */
public int compare(MilkDelivery o1, MilkDelivery o2) {

//Cast down
MilkDelivery delivery1 = (MilkDelivery) o1;
MilkDelivery delivery2 = (MilkDelivery) o2;

if(delivery1.getDaysTilExpiration() > delivery2.getDaysTilExpiration()){
return 1;    
}else if(delivery1.getDaysTilExpiration() == delivery2.getDaysTilExpiration()){
return 0;
}else if(delivery1.getDaysTilExpiration() < delivery2.getDaysTilExpiration()){
return -1;

//or a much more graceful solution....
//return (delivery1.getDaysTilExpiration() - delivery2.getDaysTilExpiration());
}
}
Last but not least, lets write a test class.
package com.company.test;

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

import com.company.model.MilkDelivery;
import com.company.model.comparator.MilkDeliveryComparator;

public class MilkTest {

public static void main(String [] args) throws Exception{

ArrayList deliveries = new ArrayList();

deliveries.add(new MilkDelivery(2));
deliveries.add(new MilkDelivery(3));
deliveries.add(new MilkDelivery(1));
deliveries.add(new MilkDelivery(4));

//Sort
Collections.sort(deliveries, new MilkDeliveryComparator());

for(int i = 0; i < deliveries.size(); i++){
MilkDelivery milkDelivery = deliveries.get(i);
System.out.println("Delivery(" + i + ")  Days til Expiration:" + 
milkDelivery.getDaysTilExpiration());
}
}
}


The output should read:
Delivery(0) Days til Expiration:1
Delivery(1) Days til Expiration:2
Delivery(2) Days til Expiration:3
Delivery(3) Days til Expiration:4

2 comments:


  1. This is a great website, so many people need this information, thanks for providing it. I love your color scheme too!

    Jin
    www.imarksweb.org

    ReplyDelete