Sort list of complex objects alphabetically

Posted on 2009-12-16
Last Modified: 2012-05-08

I need to sort a list of complex objects. Looks like this:

  class Farm {
     String name;
     Data mLotsOfData;

  List<Farm> farms = getAllFarms();

  // Now i want to build a new alphabetical list.
  TreeMap<String, Farm> alpha = new TreeMap<String, Farm>();
  for (all farms) {
      alpha.put(farms.get(i).name, farms.get(i));

  // Back to a list.
  ArrayList<Farm> alphaFarms = new ArrayList<Farm>();
  for (all in alpha) {

but it seems to not do anything -what's the right way to do this?

Question by:DJ_AM_Juicebox

    Author Comment

    Nevermind, that does work (was using package names or something for

    But is there a more efficient way?

    LVL 23

    Expert Comment

    You need to pass a comparator to the TreeMap object constructor.
    LVL 23

    Expert Comment

    Sorry... didn't check String is key..

    Thats the right way
    LVL 23

    Accepted Solution

    >>   // Back to a list.

    Can be done directly like..

    treeMap.keySet( ), will give you a Set Object with all the keys.
    LVL 23

    Expert Comment

    Moreover .. if you have getAllForms() source code..

    You can modify directly that to return a Map.. (an instance of TreeMap)

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Join & Write a Comment

    Suggested Solutions

    Title # Comments Views Activity
    Java 1603 Error 2 26
    Understanding @ResponseBody annotation 5 36
    classnotfoundexception 3 28
    nestparen challenge 4 36
    Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
    Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
    This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
    This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

    731 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now