Skip to content

Groovy Comparator for class field names


I wonder why this was not in JDK/Groovy Collections.

Just put together a Comparator for StackOverflow question – a Groovy Comparator that would sort class field names in the declaration order. Feel free to use:

class PropComparator implements Comparator {
    private Class clazz
    PropComparator(Class clazz) { this.clazz = clazz }

    int compare(Object o1, Object o2) {
        clazz.declaredFields.findIndexOf{it.name == o1} 
          - clazz.declaredFields.findIndexOf{it.name == o2}
    }
}

2 Comments

  1. arumad wrote:

    1) why would one need such functionality?
    2) compare by minus is almost a bad practice.
    p.s.1 openId would be nice.
    i hope you don’t believe those loosers who claims it’ already dead.
    p.s.2 great example for language comparison, you are trying to do here – continued fractions.
    BTW. I’m reading “Hacker Heroes” now –
    have found Gosper (author of the first such algorithm) there among first (lost of asm and a little of lisp) hackers.
    amazing. before small remark “some of that notes latter became published papers” i didn’t realize that was the same Gosper, and book was rather boring for me.
    i would never believe chained fractions was first developed in assembler before that book.

    Posted on 16-Feb-11 at 09:07 | Permalink
  2. Hi Alex,

    OpenID is almost here, had to use 3rd-party service – WordPress openId didn’t work with Google or LiveJournal, and didn’t have Facebook/VK.

    What about continued fractions, you got some samples to compare to? This, maybe? I’ll give it a look 🙂

    1. One needs it for convention-over-configuration paradigm: we’re absolutely fine with form fields going in the same order as declared in the class. Shocked?

    2. Well, it worked and it’s groovy 😀 And pretty null-safe – note it’s not Java.

    Posted on 17-Feb-11 at 00:00 | Permalink

Post a Comment

Your email is never published nor shared.