Jump to content
  • Advertisement
Sign in to follow this  
FreJa

yet another java doubt...

This topic is 4619 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
Sort the output, not the HashMap. Get all the entries as an array of Map.Entry elements and sort the array using your own comparator.

That's as much Java as I'm willing to consider.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!