http://qs321.pair.com?node_id=264889


in reply to Re: (OT) The Schwartzian Transform in Java
in thread (OT) The Schwartzian Transform in Java

The problem isn't with the comments, it's with throwing everything into one big main() method. Why throw away code when with a little bit more work you can give it some real power?
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import perlforjava.control.Looper; import perlforjava.functions.Arrays; import perlforjava.functions.Mapper; import perlforjava.lang.Block; /** * The Schwartzian Transform written in Java. */ public class TheSchwartz { private ArrayList list; /** * Comparator to sort by length. */ public final static Comparator BY_LENGTH; /** * Comparator to sort alphabetically. */ public final static Comparator ALPHABETICALLY; /** * Static initializer */ static { BY_LENGTH = new Comparator() { public int compare(Object a, Object b) { return ((Integer) ((List) a).get(1)).compareTo( ((Integer) ((List) b).get(1))); } }; ALPHABETICALLY = new Comparator() { public int compare(Object a, Object b) { String s1 = a.toString().substring(1); String s2 = b.toString().substring(1); return s1.compareTo(s2); } }; } /** * Simple Constructor. * * @param list */ public TheSchwartz(ArrayList list) { this.list = list; } /** * Workhorse function. Sorting by passed in Comparator * * @return */ public ArrayList sort(Comparator sortBy) { List out = Mapper.map(new Block() { // pull the first element from each List and return it protected Object process(Object elem) { return ((List) elem).get(0); } }, Arrays.sort( // run the comparison of Integer values to determine o +rder sortBy, // map each string into an ArrayList of string => length Mapper.map(new Block() { protected Object process(Object elem) { ArrayList temp = new ArrayList(); temp.add(elem); temp.add(new Integer(((String) elem).length())); return temp; } }, list))); return (ArrayList)out; } public static void main(String[] args) { // Create a new List of values to sort ArrayList in = new ArrayList(); in.add("fu"); in.add("duhh"); in.add("birdy"); in.add("sea"); /* Sort based upon length of string by mapping each string to a List where the first element is the string and the second + is its length. Sort on the latter and return a new List of str +ings. */ TheSchwartz merlyn = new TheSchwartz(in); List outByLength = merlyn.sort(TheSchwartz.BY_LENGTH); System.out.println("By Length:"); // Loop over the results to view them Looper.foreach(outByLength, new Block() { protected Object process(Object elem) { System.out.println("ELEM " + elem.toString()); return null; } }); System.out.println("\nAlphabetically:"); List outAlphabetically = merlyn.sort(TheSchwartz.ALPHABETICALL +Y); // Loop over the results to view them Looper.foreach(outAlphabetically, new Block() { protected Object process(Object elem) { System.out.println("ELEM " + elem.toString()); return null; } }); } }
Fun post.
()-()             
 \"/              
  `