Saturday, January 14, 2012

Simple Sorting Facade for Java (SSF4J)

In Java to sort two or more lists together you have to write a custom solution.

Say, you have list of names and corresponding list of weights. There is no API that allows you to sort names by weights (at least not that I know). However this is very common use case, especially when you analyzing data in your programs.

To achieve this, you, most likely, implement one of the sorting algorithms with a custom swap-logic.

Simple sorting facade is a pattern that already contains implementation of sorting algorithm(s) and only requires developers to specify source list, its bounds, and compare- and the swap-logic.

You can explore SSF4J on GitHub and contribute your implementations of sorting algorithms.

Here's an example of using SSF4J:


3 comments:

  1. Actually, Java-way of doing this is much-much simpler:

    1. Create a new class that contains reference to 'name' and 'weight'

    2. Make it implement Comparable that returns difference of weights

    3. Call Collections.sort() with collection of your classes.

    4. Afterwards you can extract 'names' back from sorted array.


    If sorting by weight is somehow natural to names, you can just implement Comparable on your class that contains names.

    ReplyDelete
  2. @kosiakk, I agree that in a simple cases like this you cat just merge name and weight in a single class that implements Comparable.
    But that's not always an option, I can see these cons:
    1) when you rebuild your data structures - you're, actually getting a new copy of data, which is a memory overhead that can be a problem;
    2) rebuilding your data structures for the needs of sorting may be difficult/or resulting structures may be inconvenient for the rest of the application.

    Here's one real-life example of structures that I use with ssf4j (as you can see there is also a custom get-logic):

    private Map> traces = new HashMap>();

    ...

    private void writeSummary(final List headers) throws IOException {
    SortHandler handler = new SortHandler() {
    public int to() {
    return headers.size() - 1;
    }
    public void swap(int i, int j) {
    Collections.swap(headers, i, j);
    }
    public Integer get(int index) {
    String header = headers.get(index);
    return traces.get(headerKeys.get(header)).size();
    }
    public int compare(Integer a, Integer b) {
    return a.compareTo(b);
    }
    };
    handler.sort();

    ...
    }

    ReplyDelete
  3. Blogger doesn't like java-generics, here's the same code:


    https://gist.github.com/1619412

    ReplyDelete