Sort list of complex objects alphabetically

Posted on 2009-12-16
Medium Priority
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
  • 4

Author Comment

ID: 26068378
Nevermind, that does work (was using package names or something for Farm.name).

But is there a more efficient way?

LVL 23

Expert Comment

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

Expert Comment

ID: 26068395
Sorry... didn't check String is key..

Thats the right way
LVL 23

Accepted Solution

cmalakar earned 2000 total points
ID: 26068406
>>   // 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

ID: 26068417
Moreover .. if you have getAllForms() source code..

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

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses
Course of the Month14 days, 7 hours left to enroll

807 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