List & TreeMap

Hi,
I need to implement something like pictured here:
http://cslibrary.stanford.edu/109/treelist2.gif
I need to do this with a TreeMap, so I will have O(logn) in insertion & deletion, and link the elements, so I could traverse through them in O(1).
every insertion/deletion to the TreeMap will add/remove the element to the linked list also.
I cannot use the built-in iterator(), because it's built upon call. meaning it will go have to treverse through all elements... O(n)...
10x

Hi,
I need to implement something like pictured here:
http://cslibrary.stanford.edu/109/treelist2.gif
I need to do this with a TreeMap, so I will have
O(logn) in insertion & deletion, and link the
elements, so I could traverse through them in
O(1).
every insertion/deletion to the TreeMap will
add/remove the element to the linked list also.Yes, it will. Is this what you need help with?
When you insert an object, you need to find the objects that predede and succeed that objcet in the map. You need to unlink them from each other, then create new links for the new object.
Removing an object is the same in reverse.

Similar Messages

  • How to do it in JSP

    Hi all
    Just calling only one method I get the data as follows.
    E004010001E1B520 E004010001E1B520 E004010001E1B520 E004010001E1B643 E004010001E1B678 E004010001E1B678
    What I wanna do it that this value(E004010001E1B520) appears three times, I wanna print it only once and count the number of appearance and same thing with other values(E004010001E1B643) and(E004010001E1B678).
    I mean I wanna print in a table it as follows
    Sl. No TAGID COUNT
    1 E004010001E1B520 3
    2 E004010001E1B643 1
    3 E004010001E1B678 2
    Thanx
    kvijai

    well you have evrything with now, you did find how many occurances where there too.... in order to display the result using JSP use the following class as a bean & in order to find the total number all you can do is to sum everything up.
    place SampleRfInputDemo.class at <Your_web_appln/web-inf/classes/com/RfDetect path and to the above code add an extra line right at the top pckage com.RfDetect;
    i.e
    package com.RfDetect;
    import java.util.Collections;
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.TreeMap;
    import java.util.StringTokenizer;
    * Author : rahul.a
    class SampleRfInputDemo{
    //Sample input
    static String in = "E004010001E1B520 E004010001E1B520 E004010001E1B520 E004010001E1B643 E004010001E1B678 E004010001E1B678  E004010001E1B521 E004010001E1B520 E004010001E1B678";
    /* The following method resolves the input and converts it into a Sorted List */
    public List<String> saveRfConsoleIp(String InputString) {
    ArrayList<String> SampleList = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer (InputString," ");
    while(st.hasMoreTokens()){
    String value = st.nextToken();
    SampleList.add(value.trim());
    Collections.sort(SampleList);
    return(SampleList);
    /* Final Map Which arranges data in format
    *E004010001E1B520 = <Number_of_occurances>
    public Map<String,Integer> getRfIpMap(List<String> list){
    TreeMap<String,Integer>  map = new TreeMap<String,Integer>();
    int count = 1;
    if(list.size() > 0 && list != null){
    map.put(list.get(0),count);
    for(int i=0;i<list.size() - 1;i++){
       if(list.get(i).equals(list.get(i+1)) == true)
         count = count + 1;
       else
         count = 1;        
       map.put(list.get(i+1),count);
    return(map);
    }and compile the file to genarate a new SampleRfInputDemo.class file there and then try the code mentioned below...
    <%@page language="java" import="java.util.Map,java.util.Set"%>
    <jsp:usebean id="sample" class="com.RfDetect.SampleRfInputDemo" />
    <%
    Map<String,Integer> OutPut = sample.getRfIpMap(sample.saveRfConsoleIp("E004010001E1B520 E004010001E1B520 E004010001E1B520 E004010001E1B643 E004010001E1B678 E004010001E1B678  E004010001E1B521 E004010001E1B520 E004010001E1B678"));
    int SIZE = OutPut.size();
    %>
    <html>
    <head>
    <title>Rf Indication</title>
    </head>
    <body>
    <table border="1">
    <tr>
    <th>SNO</th>
    <th>RFID</th>
    <th>COUNT</th>
    </tr>
    <%
    int totcount  = 0;
    Set key = OutPut.keySet();
    Object keys[] = key.toArray();
    for(int i = 0; i < SIZE ; i++){
    out.println("<tr><td>"+(i+1)+"</td>");
    out.println("<td>"+keys[i]+"</td>");
    out.println("<td>"+OutPut.get(keys)+"</td>");
    out.println("</tr>");
    Integer inc = (Integer) OutPut.get(keys[i]);
    totcount = totcount + inc.intValue();
    %>
    </table>
    <%
    out.println("The total count is "+totcount);
    %>
    </body>
    </html>
    However,it would be lot better if we can use JSTL instead of scriptlets for better readablity.
    Hope this helps
    REGARDS,
    RaHuL

  • Best collection for this purpose

    hai
    i am developing a system which have messaging as the main goal .different clients from remote locations have to send messages(byte array) to an MDB .But my problem is i cant control this messaging system as lot of messages have to be processed by the MDB. So i want a good collection procedure to collect the messages and there by process the messages one by one,.Can any one tell me which collection class is suitable for this or any other ideas. Thanks in advance.

    Decision procedure:
    (a) do you need a separate unique key to access the data? If so, use some form of Map. Otherwise
    (b) do you need uniqueness within the collection? If so, use some form of Set, otherwise some form of List or Queue.
    (c) If you need a Map or Set, do you need ordering? If so use a sorted Map/Set/List (TreeMap/TreeSet), otherwise a hashed Map/Set/(HashMap/HashSet). OR
    (d) if you need a List, do you need random access to inner elements? If so use an ArrayList, otherwise a LinkedList. If you only need access to the front and rear of the list consider a Queue.

  • Using a List as the value class of a Map - How?

    Hello,
    I have a managed-property of the following type
    Map<String, List<String>> myMap;How can I set the values for the List in the faces-config.xml?
    I tried sth like this, but this is no valid XML according to the schema.
    Any ideas?
    Regards,
    Jan
    <managed-property>
    <property-name>myMap</property-name>
      <property-class>java.util.TreeMap</property-class>
      <map-entries>
      <key-class>java.lang.String</key-class>
      <value-class>java.lang.ArrayList</value-class>
        <map-entry>
          <key>key1</key>
          <value>
          <list-entries>
            <value>value1</value>
            <value>value2</value>
          </list-entries>
          </value>
        </map-entry>
      </map-entries>
    </managed-property>

    You don't need a cfloop. Try an IN(...) clause instead.
    Obviously you have to validate that the #riderlist# is not empty
    first or the query will error.
    SELECT riderId,
    SUM(IIf(month(rideDate)=1, rideDistance, 0)) AS janSum,
    SUM(IIf(month(rideDate)=2, rideDistance, 0)) AS febSum,
    SUM(IIf(month(rideDate)=3, rideDistance, 0)) AS marSum,
    SUM(IIf(month(rideDate)=4, rideDistance, 0)) AS aprSum,
    SUM(IIf(month(rideDate)=5, rideDistance, 0)) AS maySum,
    SUM(IIf(month(rideDate)=6, rideDistance, 0)) AS junSum,
    SUM(IIf(month(rideDate)=7, rideDistance, 0)) AS julSum,
    SUM(IIf(month(rideDate)=8, rideDistance, 0)) AS augSum,
    SUM(IIf(month(rideDate)=9, rideDistance, 0)) AS sepSum,
    SUM(IIf(month(rideDate)=10, rideDistance, 0)) AS octSum,
    SUM(IIf(month(rideDate)=11, rideDistance, 0)) AS novSum,
    SUM(IIf(month(rideDate)=12, rideDistance, 0)) AS decSum
    FROM mileageLog
    WHERE riderId IN (<cfqueryparam value="#riderList#"
    cfsqltype="the column type here" list="true"> )
    AND Year(rideDate)=#useYear#
    GROUP BY riderId
    ORDER BY riderId

  • A TreeMap and ArrayList question

    I am considering using a TreeMap structure with a String as my key and an ArrayList<Record> as my value. After doing some searching and not quite finding the assurance I desired, I am looking for anyone's guidance on my approach. Allow me to briefly explain my situation.
    I am writing a program which reads a entry log and breaks the information into a more usable form (in particular, separated by each individual). I do not know before hand the names of the people I may encounter in the log, nor how many occurances of their name I may find. Also, it is safe to assume that no one person's name is the same for two different people. I wish to be able to call up a person's name and view all records associated with them. I felt the use of a TreeMap would be best in the event that I wish to list out a report with all individuals found, and such a listing would already be in alphabetical order.
    In summation, is my approach of making a TreeMap<String, ArrayList<Record>> an acceptable practice?
    Thank you for your time.

    Puce wrote:
    >
    If there's the slightest chance, OP, that you'll have to do something other than simply look up records by name, consider an embedded DB. If there's the slightest chance that Ron Manager will come along on Monday and say "Good job! Now, can we look up records by date?" or something, consider an embedded DB."Embedded DB" is something different than "in-memory DB" though. An embedded DB is persistent while a in-memory one is not. If you use an embedded DB, you need to synchronize it after restart with your other data sources, and it will use disk space as well. There are use case for embedded DBs and others for in-memory DBs. Hard to say which is the case here, without knowing more.The OP "isn't allowed" to use a database, which almost certainly means he's not allowed to install any more software on the system, eg, MySQL. So an in-process database is the way to go. Whether it's persistent or not is irrelevant. "Embedded" and "in-memory" are not opposites. By "embedded" we really mean in-process. Do you know of any databases which can run in-process but not in-memory? How about in-memory but not in-process? In reality, we're talking about the same products, configured slightly differently.

  • Hashmap, Lists and Indexing

    Ive had this design problem come up twice already (in the last 3 weeks)
    so i figured its time to consult the sages.
    Though I know how to use a hashmap in
    code I dont really know anything technical about them (or any other map
    or hash---). I dont really have a grasp when to use them over ArrayList
    or LinkedList aside from obvious key/value situations.
    I see them used almost everywhere (I use them almost nowhere). I hear they are faster than get() methods in Lists (which I use always).
    Anyway, this is my requirement:
    I have an object that has a unique index (ordering value).
    this index isnt the position that the object has in the list its just some number or numbers that are sortable and unique (and usually not
    consequtive).
    Example:
    13
    105
    106
    418
    2107
    (not 1, 2, 3, 4, 5)
    I could have from 0-30,000+ of these objects. Right now im using a LinkedList because from what I understand they are better for random insertion (which there will be a lot of).
    Because I dont have technical knowledge of Hashmaps i dont
    use them - but I thought the index numbers would make good keys (theyre guarenteed to be unique).
    Heres the problem. When I grab a random object I (as a requirement)
    need to be able to get the previous/next object. Using the example above: if im at object indexed 105 id need to know that object indexed
    13 is the previous entry in the collection.
    I did research this and the Hashmap API specifically says:
    "This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time."
    So Hashmap is unuseable for my purposes right?
    Right now i am using a binary search with a comparator to always
    insert objects into the LinkedList sorted ascendingly by that index number. I am using the same binary search and comparator to then retrieve an object quickly. To grab the previous object I get the object
    in the previous element and grab its index number.
    So my question is: are my assertions correct? is my linkedlist with a
    binary search for keeping it sorted and quickly accessible an ok method?
    thanks for any input!

    Thanks. The indices are unique.
    How do you get the previous entry in a TreeMap
    (because you wont
    have the key)?I think you would have to maintain a copy of the keys in an ArrayList and use Collections.sort() every time a new key is added/removed. Use the ArrayList to randomly pick a key and its adjacent keys which you would then in turn use to retrieve the object from a Map (because order here don't matter anymore).
    Message was edited by:
    CodeOnFire-again

  • Use an HashMap, an TreeMap or just an array?

    Hi,
    i have a fixed size of graph nodes, lets say 100.000.
    Each of these nodes should have an own id, where i just would take the node number - if i increment on these nodes - as such an id.
    Suggestion a)
    If i safe them to an HashMap, the key is the id as
    nodeCounter = 0;
    HashMap h = new HashMap(100.000);
    h.put(new Integer(nodeCounter++), nodeInstance);
    //...put in  all nodes-> To search for a node would be constant time O(1)
    -> What about insertion, also O(1)?
    Suggestion b)
    if i safe it to a TreeMap i would have also the key as the id and put in all
    the nodes. Since the key is just an unique Integer from 1-100.000 a
    comparator can be used to keep the RedBlackTree sorted.
    -> To search for a node would cost O(log(n))
    -> To insert a node would cost O(log(n))
    Suggestion c)
    Since a node is just represented on screen by his id and a fixed String as Node"+"1" -> "Node 1" i thought of using an simple array to safe the nodes, since each index of the array is just the id of the node.
    -> To find a node costs O(1)
    -> To insert a node is dynamically not possible
    My preferring suggestion is a)
    but only if the insertion an finding of an node is both constant O(1).
    Is it an advantage for a TreeMap to keep
    the elements sorted, compared to a HashMap which keeps them unordered?
    What do you think?
    Do you have any good advice for me or any other good alternative how to solve this problem? By reaching best performance?
    Thanks a lot for your answer!
    Message was edited by:
    Cinimood

    ok, thanks for your answer - i will describe the whole problem i want to solve:
    given is an undirected graph of nodes, let�s say a network graph.
    This graph contains about 1000 nodes(less or 2000 or 3000 is also possible), where the nodes are linked by each other -
    could be a full mesh in the worst case. Each link is assigned a weight.
    The features this graph should provide are:
    - adding a node when the graph is already created i.e. represented by the datastructure.
    - searching for a link between two nodes
    To represent a graph by a datastructure is best by using an adjacency matrix or an adjacency list.
    Searching for a link between two nodes the adjancency matrix provides best performance by just O(1). But the adjacency
    matrix needs memory by O((n^2)/2) -> divided by 2, because the graph is undirected, O(n^2) in a directed graph.
    ok, using an array like:
    Node nodes[] = new Nodes[1000]; is of course best to retreive each node by just his id which is equivalent to his index -> node[1] has id 1.
    but if i�m using an array, i cannot add another node dynamically.
    (Note: I need Node instances because each node holds its x and y coords for displaying, which is not important
    now.)
    Now, i think of a solution like this - with focus on adjacency matrix and HashMap without regarding adjacency list:
    use an adjacency matrix for searching for the specific link between two nodes because of the good performance of O(1). Because the graph is undirected i only need the upper(or lower) part of the diagonal of the matrix,
    thus O((n^2)/2) memory.
    use a HashMap for the nodes, where the key of the node entry for the HashMap is just his ID:nodeMap.put(new Integer(nodeCounter++), nodeInstance);use a HashMap for the links between the nodes, where a link is represented by the class Link which holds just the weight.
    To identify the link, use an ID which consists of the concatenation row+column of the adjacency matrix e.g.
    row = 1, column = 2 -> ID = 12
    linkMap.put(new Integer(row+column), new Link(weight));-> if i want to insert a weighted link between node 2 and node 5 i just modify the Link object in the linkMap which has the
    key 2+5 -> 25.
    That�s what i want to do and what makes me thinking all the time of good performance,
    because a lot of nodes might exist and searching, deleting and inserting must be quick.

  • The truth about objects, references, instances and cloning (Trees and Lists

    Hello
    As a few of you may have know from my postings over the past few weeks, ive been building my first real java ap and trying to learn along the way, hitting a few snags here and there.
    One main snag i seem to have been hitting a fair bit is objects and instances, im kinda learning on how they work and what they mean but as a php programmer it seems to be very different.
    as pointed out to me if you have objectA=objectB then in php you have two objects that share the same value but in java you have still one object value and one object pointing to the value.
    sooo my first question is
    if i have this
    Object objA=new Object()
    Object objB=objA()then object A creates a new memory allocation for the object data right? and object B is simply a reference to the object A memory allocation right?
    so therefore there is no instance of objectB? or is there an instance of object B but it just takes up the same memory allocation as object A?
    anyway, what is the point of being able to say objB=objA what can that be used for if not for making a copy of an object (i understand now that it doesnt copy an object)
    My second question (which i think i actually understand now, but im posting it to see if the answers may help others)
    If i have a List structure (e.g. arraylist) then when i add a datatype such as a treemap does it not add the changed treemap, ill try and explain with code
    ArrayList mylist=new ArrayList()
    Treemap myTree=new Treemap()
    myTree.put("hello","howdy");
    myTree.put("bye","cya");
    mylist.put(myTree);
    System.out.println(mylist.toString());
    myTree.put("another","one");
    mylist.put(myTree);
    System.out.println(mylist.toString());now to be honest ive not actually tried that code and it may actually procude the right results, but from my experience so far that similar sort of thing hasnt been working (by the way i know the above code wont compile as is :p)
    anyway what i assume is that will output this
    [Hello,howdy,bye,cya] <<this is the first system out
    [Hello,howdy,bye,cya,another,one  <<this is the second system out
    Hello,howdy,bye,cya,another,one] <<this is the second system out
    where it should produce this
    [Hello,howdy,bye,cya,
    Hello,howdy,bye,cya,another,one]
    Why when I update the treemap does the arraylist change, is this because the thing that is being put in the array list is infact not an object but simply a reference to an object?
    thanks for everyones help so far :)

    as pointed out to me if you have objectA=objectB then
    in php you have two objects that share the same value
    but in java you have still one object value and one
    object pointing to the value.Some years ago, I built a small website managing data saved in an XML file using PHP. Being used to Java, I used an OO approach and created classes managing data structures and having setter/getter methods. The fact that PHP did actually create a copy of any object being passed as and argument made me crazy. This way, I wasn't able to reach the same instances from several different places in my code. Instead, I had to put a certain operator ("&" I think) before any reference to force PHP not to make a copy but pass the reference. I also found a note on the PHP site saying that copying was faster than passing the reference, which I actually couldn't believe. If I'm not wrong, they changed the default behaviour in PHP5.
    if i have this
    Object objA=new Object()
    Object objB=objA()then object A creates a new memory allocation for the
    object data right? and object B is simply a reference
    to the object A memory allocation right?The statement "new <Class>" allocates memory. The reference itself just takes up a few bytes in order to maintain some administrative data (such as the memory address). References are basically like pointers in C, though there's no pointer arithmetics and they can't point to any arbitrary place in memory (only a legal instance or null).
    so therefore there is no instance of objectB? or is
    there an instance of object B but it just takes up
    the same memory allocation as object A?There is an instance of objectB, but it's just the same instance that objectA is pointing at. Both references objectA and objectB contain the same memory address. That's why they'd produce a result of "true" if compared using the "==" operator.
    anyway, what is the point of being able to say
    objB=objA what can that be used for if not for making
    a copy of an object (i understand now that it doesnt
    copy an object)Sometimes you don't want to make a copy, as 1) it consumes more memory and 2) you'd lose the reference to it (making it more difficult to tell what instance is actually accessed). If there was no way to pass a reference to an object into a method, methods wouldn't be able to affect the original instance.
    Why when I update the treemap does the arraylist
    change, is this because the thing that is being put
    in the array list is infact not an object but simply
    a reference to an object?The ArrayList doesn't change at all. It's the instance that's being changed, and the ArrayList has a reference to it.

  • Using a treemap for lookup in a jsp grid

    Hi
              I am trying to use a treemap to lookup the names for id´s in a table.
              for example.
              Lookup table:
              ID.....Name
              1......carrot
              2......bananna
              the main table looks like this:
              row....id
              1.......2
              2.......1
              3.......1
              4.......2
              in my jsp page I want it to look like this:
              row....id
              1......bananna
              2......carrot
              3......carrot
              4......bananna
              I have the lookup table loaded into a treemap in the begin part of my pageflow.
              is there a special way that I can refer to the treemap in a grid view, for example, with a netui-data:expressionColumn ?
              thanks for any help.
              /Nigel
              Message was edited by NigelGuest at Feb 3, 2005 2:34 AM

    hi,
              important here to aknowledge that the {} databinding are compile time. This implies a whole lot of restrictions. The scenario below works for me:
              - getLookupMap in the pageflow returns the lookup map
              - getList in the pageflow returns the list
              The following code then works for me
              <!-- in the heading of my JSP -->
              // get the lookup map into pagecontext
              <netui-data:getData resultId="lookup"
              value="{pageFlow.lookupMap}"/>
              // pull down as a new page attribute
              <%
              Map lookup = (Map)pageContext.getAttribute("lookup");
              %>
              Now, in my repeater ( of gridview ) I implement the column showing the actual mapped value like this:
              // to get the item key
              <netui-data:getData resultId="key"
              value="{container.item}"/>
              // to set the mapped attribute value
              <%
              pageContext.setAttribute(
              "lookupValue",
              lookup.get(pageContext.getAttribute("key")));
              %>
              // to render the mapped attribute value
              <netui:label value="{pageContext.lookupValue}"
              defaultValue=" " />
              Probably not exactly what you asked for, but hopefully close enough to guide you in the right direction.
              - Anders M.

  • List/Enumeration of Elements in a View (WD for Java)

    Hello,
    How do I get a complete list of all elements in a view at runtime?
    I want to dynamically modify 30+ elements, but I don't want to have to code each of them. Is there a way to do this?
    Thanks,
    Martin

    Martin,
    Try something like this:
    static interface IAction
      abstract public void execute(IWDUIElement el);     
    static class CollectElements implements IAction
      final private Map _result = new TreeMap();
      public Map result() { return Collections.unmodifiableMap(_result); }
      public void execute(final IWDUIElement el)
        _result.put( el.getId(), el );       
    void traverse(final IWDView view, final IAction action)
      traverse( (IWDUIElementContainer)view.getRootElement(), action );
    void traverse(final IWDUIElementContainer container, final IAction action)
      action.execute(container);
      for (final Iterator i = container.iterateChildren(); i.hasNext(); )
        final IWDUIElement el = (IWDUIElement)i.next();
        if ( el instanceof IWDUIElementContainer )
          traverse( (IWDUIElementContainer)el, action );
        else
          action.execute( el );
    Sample:
    final CollectElements selectAll = new CollectElements();
    traverse(wdView, selectAll);
    /* Now selectAll.result() contains id->element mapping */
    This will not collect Table columns, or Tabs in TabStrib, however you can create "dispatching" IAction implementation, that delegates to some custom methods like traverse(IWDTable) or traverse(IWDTabStrip)
    Valery Silaev
    EPAM Systems
    http://www.NetWeaverTeam.com

  • Sorting problem in TreeMap, please help urgent :-((

    Hi
    Following is a program, please execute it to see the problem. I am adding four elements in the TreeMap. The problem is when I add the elements it never compares the newly added element with the first element. I was sick of it so to test the TreeMap I created my own small class and defined a Comparator for that class. Following is the code which shows the problem in TreeMap. Am I doing something wrong? Please help its urgent.
    import java.util.*;
    public class SortingCollection {
         public static void main(String[] args) {
              SortingCollection sortingCollection = new SortingCollection();
              sortingCollection.sortingTest();
         public void sortingTest() {
              TreeMap treeMap = new TreeMap();
              treeMap.put(new Test("Bhushan", 1022), new Integer(1022));
              treeMap.put(new Test("Wasil", 1023), new Integer(1023));
              treeMap.put(new Test("Ifti", 1020), new Integer(1020));
              treeMap.put(new Test("Roshan", 1021), new Integer(1021));
              System.out.println(treeMap);
              Test test = new Test("Bhushan", 1028);
              treeMap.put(test, new Integer(1022));
              System.out.println(treeMap);
         public class Test implements Comparable {
              public String name;
              public int age;
              public Test(String name, int age) {
                   this.name = name;
                   this.age = age;
              public int compareTo(Object toBeCompared) {
                   Test casted = (Test) toBeCompared;
                   if (name.equals(casted.name)) {
                        System.out.println("Returning 0 for " + name + " " + casted.name);
                        return 0;
                   System.out.println("Returning -1 for " + name + " " + casted.name);
                   return -1;
              public String toString() {
                   return "[" + name + ", " + age + "]";
    }

    If you are using TreeMap, you should want the keys to be immutable. You can't change the state of the keys of a Map such that their natural order will change, or chaos will happen.
    If the key is the GateKeeperInfo class (which has host, port, and # of users as its data members) and the value is "some other object reference which you need", and this reference is closely tied to the GateKeeperInfo, have you considered making it a member of the GateKeeperInfo?
    That way you don't need this TreeMap business. You can have the natural ordering imposed on the GateKeeperInfo class (which is apparently comparing the host and port only). You can also have a Comparator object that can compare these objects in a different way (# of users, for instance).
    public class MyClass implements Comparable
       String host;
       int    port;
       int    currNumUsers;
       Object someOtherObjectReferenceINeed;
       // or if the object reference you need is an Integer, make that last member
       // an int...
       // Also, let's keep a Comparator in here for comparing # of users.
       // See further down for actual implementation...
       public static final Comparator BY_NUM_USERS = new NumUsersComparator();
         // Use the equal methods to determine whether or not host and port matches
       public boolean equals( Object obj )
       // Use the compareTo method to compare 2 instances in terms of host and port
       public int compareTo( Object obj )
         // Make this object take care of changing # of users, outside of the
         // Comparable interface.
         public int getNumUsers();
         public int bumpNumUsers( int byThisAmount ); // changes # of users...
         // Beef up this object to take advantage of someOtherObjectReferenceINeed
    // Use this Comparator object to compare 2 instances of MyClass
    // according to # of users.
    public class NumUsersComparator implements Comparator
         public int compare( Object a, Object b )
              MyClass left      = (MyClass)a;
              MyClass right      = (MyClass)b;
              // I am assuming both # of users are of the same sign...positive
              return ( right.getNumUsers() - left.getNumUsers() );
    // Now when you need to compare, you can do it 2 different ways...
    // You can use whatever Collection you fits, List, Set, ...
    // I am going to use List in this case
    List gateways = new ArrayList;
    // add the objects...
    gateways.add( /* . . . */ );
    // Now let's sort in terms of user/port
    Collections.sort( gateways );
    // Let's sort in terms of number of users...
    Collections.sort( gateways, MyClass.BY_NUM_USERS );
    // I am going to mix them around now...
    Collections.shuffle( gateways );
    // Now let's find the gateway w/ the largest # of users...
    MyClass currMaxGateway = Collections.max( gateways, MyClass.BY_NUM_USERS );
    .

  • Change Highscore list from ASC to DSC. Urgent

    Hi guys. I need help with changing the sort type of this code.
    I write the output in an jTextArea Field with Descending order. it looks like
    Viktor = 40
    Thomas=65
    Emil=30
    Alfred=120
    so you see that the names are sorted. i want the points (score) to be sorted.
    The data is saved into an properties file which looks so
    #Highscore-Properties
    #Mon Jan 22 22:12:48 CET 2007
    Viktor=80
    Dora=90
    Hans=200
    Bertie=1000
    Sepp=400
    public HighScore()
            throws Exception
                myScore.load(new FileInputStream(System.getProperty("user.dir") + File.separator + "score.properties"));
        /* returns Sortedmap mit key = Playername & Value-Score */
        public SortedMap getScoreList()
            SortedMap score = new TreeMap();
            Enumeration keys = myScore.keys();
            if (keys != null)
                while (keys.hasMoreElements())
                    String tname = keys.nextElement().toString();
                    score.put(tname, myScore.getProperty(tname));
    // HOW TO CHANGE THIS PIECE OF CODE?
                return score;
            return null;
        /* If player is in properties list and score is higher than the new
         * then it writes the higher score in the file.
         *@param nickname = player
         *@param score = Highscore
        public void setnewScore(String nickname, int score)
        throws Exception
            if (myScore.getProperty(nickname) != null && Integer.parseInt(myScore.getProperty(nickname).toString()) < score)
                myScore.setProperty(nickname,""+score);
                myScore.store(new FileOutputStream(System.getProperty("user.dir") + File.separator + "score.properties"),"Highscore-Properties");
            else if (myScore.getProperty(nickname) == null)
                myScore.setProperty(nickname, ""+score);
                myScore.store(new FileOutputStream(System.getProperty("user.dir") + File.separator + "score.properties"),"Highscore-Properties");
    I wrote the main method in my other visual class when the window is activated
    instead of the system.out.println i wrote
    jTextArea2.setText("Spieler: " + player + " Score: " + sm.get(player)+"\n"+jTextArea2.getText());
    writes all players who are in the score list (alphabetical ordered)
         *@param args
        public static void main(String[] args)
            try {
                HighScore hs = new HighScore();
                SortedMap sm = hs.getScoreList();
                Iterator ene = sm.keySet().iterator();           
                while (ene.hasNext())
                    Object player = ene.next();
                       System.out.println("Player: " + player +" Score: " +sm.get(player));
            } catch (Exception e)
                e.printStackTrace();
    }       I am sorry for my bad english.
    It would be very nice if someone could tell me what to change in my code.
    ty
    Message was edited by:
    Shadowli

    yes... the set and get scorelist is not from me.
    the tipp is good, but i can not code it because i am extreme java newbie.
    so it would be very nice if i get the pieces of code i need because i need the highscore list till tomorrow.
    in the meantime i tried other way round. set from nickname=score to score=nickname but because of the enumeration it sorts like
    50 hans
    30 thomas
    20 emil
    205 name
    19 name
    1394 emil
    0 name
    so please help me.

  • Sorting large amounts of data with treemap

    Hello. Im doing a project where I have to sort a large amount of data. The data is formed by a unique number and a location (a string).
    Something like this
    NUMBER .... CITY
    1000123 BOSTON
    1045333 HOUSTON
    5234222 PARIS
    2343345 PARIS
    6234332 SEATTLE
    I have to sort the data by location and then by unique number...
    I was using the TreeMap to do this : I used the location string as a key - since I wanted to sort the data by that field - but, because the location string is not unique, at the moment to insert the data on the TreeMap, it overwrites the object with the same location string, saving only the last one that was inserted.
    Is there any Collection that implements sorting in the way that I need it?... or if there isnt such thing... is there any collection that supports a duplicated key object???
    Thanks for your time!
    Regards
    Cesar

    ... or use a SortedSet for the list of numbers (as the associated value for
    the location key). Something like this:voidAddTuple(String location, Integer number) {
       SortedSet numbers= set.get(location);
       if (numbers == null)
          set.put(location, numbers= new TreeSet());
       numbers.put(number);
    }kind regards,
    Jos

  • Sorting TreeMap

    Hi,
    I've been trying to work this out and can't seem to find a solution. I have a treemap of object and I want to sort them by their names, such as lastname. These object hold all these datas. I wrote myself a comparator class like this:
    import java.util.*;
    import java.io.*;
    public class PatientComparator implements Comparator {
    public int compare(Object obj1, Object obj2) throws ClassCastException {
    System.out.println(obj1.getClass()); //use to see what is passing in to compare
    Patient a = (Patient)obj1;
    Patient b = (Patient)obj2;
    String nameA = a.getName();
    String nameB = b.getName();
    String firstName = nameA.substring(0,nameA.indexOf(",",0)-1);
    String lastName = nameA.substring(nameA.indexOf(",",0)+1,nameA.length()-1);
    String firstName2 = nameB.substring(0,nameB.indexOf(",",0)-1);
    String lastName2 = nameB.substring(nameB.indexOf(",",0)+1,nameB.length()-1);
    int result = 0;
    if ( !(lastName.equals(lastName2)) )
         result = lastName.compareTo(lastName2);
    else
    result = firstName.compareTo(firstName2);
    return result;
    I have to use TreeMap or HashMap right now because they both utilize the assigned key to identify object quicker. But the culprit is how do I sort this TreeMap in term of object properties(like name, age). Here is the class I implement it:
    public class DoctorsOffice {
    private String office_name;
    private int ID = 1000; //start out with id # 1000
    private SortedMap active = new TreeMap(new PatientComparator());
    //private SortedSet inactive = new TreeSet();
    * Constructor for a DoctorsOffice object.
    * @param name Name of this Dr's Office
    public DoctorsOffice (String name) {
    office_name = name;
    * Add a new patient to the office. The identification
    * number is uniquely generated and is returned when the
    * Patient object is added to the database. ID numbers
    * start at 1000 and increment by one for each new Patient
    * added.
    * @param firstName first name of this patient
    * @param lastName last name of this patient
    * @param age age of this patient
    * @return the ID number assigned to this Patient
    public int addPatient (String firstName, String lastName, int age) {
    Patient new_patient = new Patient( firstName,lastName,age );
    active.put( new Integer(ID), new_patient );
    ID++;
    return (ID - 1);
    * Remove this patient from the master database. Removed patients are
    * archived in an "inactive" database which maintains Patron
    * objects in the order in which they were removed from the master
    * database.
    * @param patientNo     Patient number assigned
    * @exception throws a NoSuchPatientException
    * if this patient does not exist
    public void removePatient (int patientNo)
    throws NoSuchPatientException {
    * Add a new medication for this patient.
    * @param patientNo     Patient number
    * @param medicationName     Name of this medication
    * @param isGeneric     True if a generic drug
    * @exception throws NoSuchPatientException if
    * this patient ID does not exist.
    public void addMedication(int patientNo, String medicationName,
         boolean isGeneric ) throws NoSuchPatientException {
    if ( active.containsKey(new Integer(patientNo)) ) {
    ((Patient)active.get(new Integer(patientNo))).recordNewMed(
    medicationName, isGeneric );
    else
         throw new NoSuchPatientException();
    * Print the medication detail for this patient. Print
    * the patient's full name (lastname COMMA SPACE firstName)
    * then each medication (each one on a new line). To print
    * the medications, simply call your toString() method in
    * the Medication class.
    * If this patient has no medication history, print "No Medications
    * Prescribed".
    * @param patientNo     Patient number
    * @exception throws NoSuchPatientException
    * if patient does not exist.
    public void printMedicationDetail (int patientNo)
         throws NoSuchPatientException {
    Integer patientID = new Integer(patientNo);
    if ( active.containsKey(patientID) ) {
    System.out.println( ( (Patient)active.get(patientID)).getName() );
    ((Patient)active.get(patientID)).printMedicationHistory();
    else
    throw new NoSuchPatientException();
    * Print all patients ordered by last name, then first name if
    * you encounter two patients with the same last name.
    * To print the Patient objects, simply call your toString() method
    * in the Patient class.
    public void listByName() {        
         // Collection coll = active.values();
    // List temp = new ArrayList(coll);
         // sort(temp,new PatientComparator());
    // Set s = temp.keySet();
    Iterator iterator = active.iterator();
    while( iterator.hasNext() ){
         // String key = (String)iterator.next();     
         System.out.println(iterator.next());     
    }

    I guess I go with the easiest way to do it. But here's
    another culprit, since values() method turn my
    TreeMap into a collection(interface), It doesn't turn the TreeMap into anything. That is, the original TM still exists, exactly as you left it. There's just a new Collection created that refers to each of the TM's values.
    and the sort()
    method is in class Collections, how do I call the
    sort(), and also the sort() method has two parameters
    (List list, Comparator C)If your values implement Comparable, and you want to use the natural sort order (for instance, the values are Strings and you just want them sorted alphabetically), then you just call the sort method that takes a single List parameter. Otherwise (for instance, you want to reverse the sort order, or sort by length, etc.), you have to write a Comparator for your values.
    >
    1st) I don't have any list to put as parameter.Both LinkedList and ArrayList take a Collection as a constructor arg, I think, so you can construct one from the Collection returned by values().
    2nd) Comparator C will keep comparing two keys from
    the treemap or in the collection?
    Collection coll = active.values();
    Collections.sort( , new
    PatientComparator());The TreeMap's Comparator will do that. The values List will sort however you tell it to, regardless of how the TreeMap sorts its keys.
    I don't think the sort is able to be called this way,
    and what do I substitute in for a parameter list when
    I have a treemap right now? Huh?

  • TreeSet, TreeMap or Comparable?

    I'm simply tackling this problem concerning a list of employee's and their division # within a company...
    Misino, John          8
    Nguyen, Viet                          14
    Punchenko, Eric          6
    Dunn, Michael          6
    Deusenbery, Amanda          14
    Taoubina, Xenia          6They're suppose to be stored in alphabetical order...My thing is, should this be approached using TreeSet, TreeMap or Comparable...From what I understand each one is, both TreeSet and TreeMap are both red/black tree implemenations of a binary search tree and TreeSet stores data with an element and a TreeMap a seperate key is created and stored in the collection while the data is stored somewhere else...Comparable seems to be used by either method considering that they are sorted and put into order in either case...Inputs anyone? I believe the information above is true, but they seem very similiar in characteristic, to me at least...

    If you're going to put it into a TreeSet or TreeMap,
    either it needs to implement Comparable, or you need
    to provide a Comparator.
    Implement Comparable if there's a sensible "natural"
    way to sort it--e.g. by last name then first, or by
    employee ID. Provide a Comparator if you want to sort
    by some arbitrary criteria that aren't necessarily a
    "natural" way to sort this class--e.g. years of
    service.
    Whether you use the Set or the Map depends on how you
    will access the elements. Will you just iterate over
    them sequentially (Set) or will you need to access
    them at random by some key (Map)?This list will be sorted by last name only...And yeah, I suppose a lot of the factor using either Set or Map depends on the accessing of elements - In general though, I think that TreeMap would be sufficient because doesn't it provides guaranteed log(n) time cost for the containsKey, find/get, insert and remove/delete operations...

Maybe you are looking for

  • Voice Mail upgrade

    Hii, In this moment I have a virtual machine with Unity 8.6.2 installed and I have to upgrade to 10.5. Any information about the steps or anyone ho finis the upgrade? Any documentation/links will more then OK. Thanks a lot

  • Oracle's Locking Architecture

    I'm specifically talking about 9i & 10G. Is there any info that explains Oracle Locking mechanisms? I tried to find something on metalink but all I found was how to detect locks. I need to start from the beginning so that I understand the lock types

  • How do I get Disney films in Italian?

    I have purchased a couple of films such as Frozen, for my toddler and she loves them. We live in the UK, so only have UK credit cards and an address however we are trying to raise her in a multilingual environment. I would love her to be able to watc

  • No lo puedo ver con Explorer

    Mi web contiene una animacion de Edge Animate CC y se ve perfectamente en Chrome pero no se ve nada (en blanco) en Explorer 11 (windows 8.1) ¿alguien me puede ayudar? Muchas gracias

  • Unable to Import VOs using server.xml

    I am a newbie to OAF.I am trying to make a setup for extending a View Object in Jdeveloper. I installed Jdev from Patch : p6012619_11i_GENERIC. Steps taken : -Created new OAWorkspace.jws and new OAProject.jpr -Imported the required .xml page -Downloa