Skip to main content
GameDev.net gamedev.net
🔒 Locked

yet another java doubt...

Started by FreJa Nov 28, 2005 at 5:54 AM 1 replies 650+ views
Original Post
FreJa
FreJa
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
"Through me the road to the city of desolation,Through me the road to sorrows diuturnal,Through me the road among the lost creation."
Oluseyi
Oluseyi
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.
Stani R
Stani R
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());  }}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.