Mar 04

Java provides a convenient Collections.sort() method to sort a List of Object’s. The Objects in the list are required to implement the Comparable interface and the compareTo() method is used to compare Objects.

When an alternate sort order is needed you can do that using a Comparator which is passed to the sort() call.

The following example shows how you could sort a list of strings where the string contained a number (that should be sorted numerically) and a string (to be sorted alphabetically).

List<String> list = Arrays.asList(
   new String[] { "34 abc", "123 dfd", "34 xyz", "12 xxx" });

Collections.sort(list, new Comparator<String>() {

	@Override
	public int compare(String s1, String s2) {

		// separate the number and string

		String[] tokens1 = s1.split(" ");
		String[] tokens2 = s2.split(" ");

		// compare the number from each item

		int compare = Integer.parseInt(tokens1[0]) - Integer.parseInt(tokens2[0]);

		// If number same compare the string

		return compare==0 ? tokens1[1].compareTo(tokens2[1]) : compare;
	}
});

written by objects \\ tags: , , ,

Oct 11

The DBUtil library from Apache provides a set of class for doing a variety of standard database tasks.

eg. To make a query becomes as simple as the following, providing the result set as a List of arrays where each list elements contains a row.


QueryRunner runner = new QueryRunner();
ArrayListHandler handler = new ArrayListHandler();
List<Object[]> result = runner.query(connection,
    "SELECT * FROM MyTable WHERE name=?", handler, "Joe Smith");
DbUtils.close(conn);

written by objects \\ tags: , , , ,

Sep 23

The readLine() method of java.io.BufferedReader class reads the next line from a text file. When it reaches the end of the file it will return null.


List<String> lines = new ArrayList<String>();
BufferedReader in = new BufferedReader(new FileReader(filename));
String line = null;
while (null!=(line=in.readLine()))
{
   lines.add(line);
}
in.close();

// lines will now contain the contents of the file

written by objects \\ tags: ,