Sign in to follow this  
FreJa

yet another java doubt...

Recommended Posts

Hi, I have this class:
public class Class1 {
   private int _id;
   private String _name;
  
   public Class1() {
      ...
   }
   ...
}
and i've created this collection:
Map<Integer, Class1> _stuff = new HashMap<Integer, Class1>();
now, i want to print _stuff into the screen, like:
_id - _name
but sorted alphabetically acording to _name. How can I do this? Huge thx

Share this post


Link to post
Share on other sites
You can use Arrays.sort(), but you'll have to have Class1 implement the Comparable interface.

Edit: Or pass a custom Comparator-derived class, as said above. For instance something like this (untested):


public class NameComparator implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = ((Class1)o1).getName();
String s2 = ((Class1)o2).getName();
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this