• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 267
  • Last Modified:

Sort list of complex objects alphabetically

Hi,

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) {
      alphaFarms.add(it.getValue());
  }

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

Thanks
0
DJ_AM_Juicebox
Asked:
DJ_AM_Juicebox
  • 4
1 Solution
 
DJ_AM_JuiceboxAuthor Commented:
Nevermind, that does work (was using package names or something for Farm.name).

But is there a more efficient way?

Thanks
0
 
cmalakarCommented:
You need to pass a comparator to the TreeMap object constructor.
0
 
cmalakarCommented:
Sorry... didn't check String is key..

Thats the right way
0
 
cmalakarCommented:
>>   // Back to a list.

Can be done directly like..

treeMap.keySet( ), will give you a Set Object with all the keys.
0
 
cmalakarCommented:
Moreover .. if you have getAllForms() source code..

You can modify directly that to return a Map.. (an instance of TreeMap)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now