Hi!

> Bhangale, Bhushan wrote:
> > I have a datastructure as following:-
> > Key - Value
> > S1  - 23
> > S6  - 12
> > S3  - 4
> > S4  - 7
> >
> > I have to sort on values. I want the key object S3 as its value is the
> > least. How to go about this?
> >
> > I have already done that using TreeMap, but indirectly as TreeMap sorts
on
> > Key and not on value. I am looking for straightforward solution if any.
> >
> > Actually S1,S2... are servers and values are number of user connected to
it.
> > For doing loadbalancing I am doing this and want the least loaded
server.

Actually I would choose to change keys to values and vice versa.

But try this code:

class ServerData implements Comparable {
    int val;
    Server key;
    public ServerData(int v, Server s){val=v; key =s;}

    public synchronized void dec(){val-=1;}
    public synchronized void inc() {val+=1;}

    public int compareTo(Object o) {
        if (o==null)    return -1;
        if (!(o instanceof ServerData))    return -1;
        ServerData sd = (ServerData)o;
        return val - sd.val;
    }
}

In your client code you have a list of servers:
List serverList = new ArrayList();
That's sorted by Collections.sort(serverList);
With serverList.get(0) you'll get the S�rverData object with the smallest
numbe of clients.

(Here's a little program demonstrating the behaviour:
/////////////////////////////////////////////////////
import java.util.*;

public class t {

 public static void main(String[] argv) {

  List servers = new ArrayList();
  int[] vals = {45,23,5,12,9,78};
  for (int i=0; i< vals.length; i++)
   servers.add(new ServerData(vals[i],new Server()));
  Collections.sort(servers);
  System.out.println(servers);
  System.out.println("Server with min users: " + servers.get(0));
 }
}

class Server { }

class ServerData implements Comparable {
    int val;
    Server key;
    public ServerData(int v, Server s){val=v; key =s;}

    public synchronized void dec(){val-=1;}
    public synchronized void inc() {val+=1;}

    public int compareTo(Object o) {
        if (o==null)    return -1;
        if (!(o instanceof ServerData))    return -1;
        ServerData sd = (ServerData)o;
        return val - sd.val;
    }
 public String toString() { return "val = " + val;}
}
/////////////////////////////////////////////////////////////////


-mw

___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".

Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html

Reply via email to