UK Postcode Splitting in Java

4 PM April 14, 2004

A Java version of Simon Brunning's Python and RPG UK postcode splitting algorithms.

Compared to the RPG version, the Java code has the virtue of being readable, even without comments.

Compared with the Python version, the Java is more verbose. Braces aside, this is mainly due to the need to return a whole object in Java where Python returns a simple tuple. The 'guts' of the algorithm is about the same size (7 lines vs 5), thanks to Apache Commons Lang.

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Postcode {
  private String inCode = "";
  private String outCode = "";

  public Postcode(String str) {
    str = StringUtils.deleteWhitespace(str).toUpperCase();
    if (str.length() <= 4) {
      outCode = str;
    } else {
      int outEnd = str.length() - 3;
      outCode = str.substring(0, outEnd);
      inCode = str.substring(outEnd);
    }
  }

  public String getInCode() {
    return inCode;
  }

  public String getOutCode() {
    return outCode;
  }

  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }

  public static void main(String[] args)
  {
    System.out.println(new Postcode("SL18jt"));
    System.out.println(new Postcode("SL1 8jt"));
    System.out.println(new Postcode("N4"));
    System.out.println(new Postcode("GN43"));
    System.out.println(new Postcode("GN43qw"));
  }
}
By alang | # | Comments (5)
(Posted to javablogs, Software Development, Python and Java)
© 2003-2006 Alan Green