SortedSet/TreeMap ...

am writing code for Displaying data in ascending order using a TreeMap(). And am in a fix to
resolve it. The scenario is like this i am calling java classes in my application from another
application whic is fetching data for me from their database where i can't intervene. From
thisapplication I am calling a class color.java in which objects are defined as string . And I need
to get the data and display the same using my servlet in its ascending order based on its color
number.Like this
ColorNumber Location Qty Price
100 C422 100 20
150 A1100 0575 15
200 D3760 130 500
Also While making call to color.java i get data of following types
colorlocation - Varchar
colornumber - number.
colorqty - number
colorPrice. - number
The piece of java code in my file details.java is like this
Color[] Range= colorenquiry.getColordata();
SortedSet ColorMap = new TreeMap();
for (int i=0; i<Range.length(); i++){
ColorMap.put(Range.colornumber, Range[i].colorlocation.toString()+""+
Range[i].colorqty.toString()+""+Range[i].colorprice.toString());
System.out.println(ColorMap.keySet());
System.out.println(ColorMap.values());
System.out.println(ColorMap.entrySet());
Now the Problem is for few querries iam getting the sorted output as above but for queries where
data is like 50- 60 rows am finding sorted data in patches like its 100,150, 200, 300, 500, 350,
600 700 425, 800, 900, 1000, 1100, 1200, 1500,250....
Please advise or have any such working examples where i can refer.
Thanks & Regards,
I tried with a Comparator to avoid natural order of sorting pls see the code below but still geting
a Clascast exception. Is there any problem with this code too?
Overall if there is any other approach to resolve sorting of rows in ascening order. Please
suggest or any other working code which i can look into.
int[] s1;
bolean[] s2;
public void CompareAscOrder(int[] s1, boolean[] s2){
if (s1.length != s2.length){
throw new IllegalArgumentException("Wrong length...");
this.s1=s1;
this.s2=s2;
final Comparator C2 = new Comparator() {
public int compare(Object o1, Object o2) {
Object rowa[] = (Object[]) a;
Object rowb[] = (Object[]) b;
for(int i=0; i<s1.length; i++)
int col = s1[i];
int result=((Comparable)rowa[col].compareTo(rowb[col]);
if (result !=0){
if(s2[i]) return result;
else return -result;
return 0;

Well, the code you post still doesn't compile and still isn't in [code ][code ] brackets, but the following does compile and does do something sensible -- specifically, the comparator will sort MyColor object according to the field called "num" (and sort them numerically, so "100" comes after "99"). Whether that's what you want it to do, I don't know. Some hints:
(a) watch your capitalization - use initial caps for classnames only
(b) there's already a class called "Color" in java.awt -- rename your Color if you can.
(c) to re-emphasize something I said earlier, a SortedMap sorts on its keys, so the comparatory is always passed two keys (which in your original example were strings, not colors).import java.util.Comparator;
class MyColor {
    String num;
    String loc;
    String qty;
    String price;
    final static Comparator c1 = new Comparator(){
            public int compare(Object a, Object b){
                MyColor col1 =(MyColor) a;
                MyColor col2 =(MyColor) b;
                int d1 = Integer.parseInt(col1.num);
                int d2 = Integer.parseInt(col2.num);
                return  d1 - d2;
}

Similar Messages

  • 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?

  • Extract values from an object trapped in TreeMap

    I can't figure out how to get the balance of an account Object (consisting of name plus balance)which is stored in a TreeMap.
    Normally it would go like this: For example
    accounts[2].getBalance();
    Normally would return the value for the specified account.
    Can anybody help?
    Thanks.
    import java.util.*;
    class Account
        private double theBalance    = 0.00;   // Balance of account
        private String theName       = "";
    public static void main (String args[]) {
                    Account accounts[] = new Account[4];
      TreeMap  accountsMap = new TreeMap();
      accountsMap.put( "0023", new Account( "Gordon", 100.0 ) );
      accountsMap.put( "0123", new Account( "James",  200.0 ) );
      accountsMap.put( "0001", new Account( "Edward", 300.0 ) );
      accountsMap.put( "7777", new Account( "Percy",  400.0 ) );
      BankStats  bs = new BankStats();
      LinkedList  r  = bs.accountsBelow( accountsMap, 250.0 );
      System.out.println(r);
        public Account( String name, double openingBalance )
          theBalance = openingBalance;
          theName    = name;
        public double getBalance()
          // assert theBalance >= 0.00;
          return theBalance;
        public String getName()
          return theName;
        public double withdraw( final double money )
          // assert theBalance >= 0.00;
          if ( theBalance >= money  )
            theBalance = theBalance - money;
            return money;
          } else {
            return 0.00;
        public void deposit( final double money )
          // assert theBalance >= 0.00;
          theBalance = theBalance + money;
    class BankStats {
          public LinkedList accountsBelow (TreeMap accountsMap, double ammount) {
               LinkedList list1 = new LinkedList();     
             for (int i = 0; i < 10000; ++i) {    
               String no = Integer.toString(i);
               for (int z =0; no.length()<4 ; z++) {
                    no= "0"+no;              
                if (accountsMap.get(no)!= null) { 
                System.out.println   (accountsMap.get(no));  // WANT TO GET THE BALANCE FOR THE ACC       OBJECT ASSOCIATED WITH THIS KEY (String no)
               if (accountsMap.get(no)< ammount) {
                                 list1.add(accountsMap.get(no)); }
          return list1;}
          public LinkedList accountsBelowNotFrozen (Account accounts[], double ammount) {
               LinkedList list2 = new LinkedList();     
             for (int i = 0; i < accounts.length; ++i) {    
               String nam = accounts.getName();
    if (accounts[i] != null) {       
    if (accounts[i].getBalance() < ammount & !nam.endsWith("[Frozen]")) {
              list2.add(accounts[i]); } } }
         return list2;}

    Use this method call to retrieve the balance (or anything else):
    Account acc = (Account) accountsMap.get(no)
    double bal = acc.getBalance();or simply:
    double bal = ((Account) accountsMap.get(no)).getBalance();

  • How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap?

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class? These are the keys,values: TreeMap The data I'd like to Cache is (date from the file, time of the file, current time).
    import java.io.*;
    public class CacheData {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\Files";
      String output = "C:\\Files\output.txt";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      // open the Printwriter before your loop
      PrintWriter outputStream = new PrintWriter(output);
      for (File textfiles : files) {
      if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
      BufferedReader inputStream = null;
      // close the outputstream after the loop
      outputStream.close();
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      // Write Content
      outputStream.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class?
    I don't understand your question.
    If you don't know how to use TreeMap why do you think a TreeMap is the correct solution for what you want to do?
    If you are just asking how to use TreeMap then there are PLENTY of tutorials on the internet and the Java API provides the methods that area available.
    TreeMap (Java Platform SE 7 )
    Are you sure you want a map and not a tree instead?
    https://docs.oracle.com/javase/tutorial/uiswing/components/tree.html

  • 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.

  • TreeMap class and message not understood issues - help please

    Can anyone help with this one please?
    The code is the start of a Map interface/TreeMap class to hold names as keys and addresses as values (both Strings).
    I think the instance variable and the constructor are correct, but the addAddress method throws an error
    Semantic error: Message addAddress( java.lang.String, java.lang.String ) not understood by class'java.util.TreeMap'.
    I can only guess that I've overlooked something quite simple? The line at the end of the code should read
    "Replaced "old address" with "new address" for "new name" and this should only display if the key already exists in the Map,
    hence the if statement. The keys and values have been declared as Objects for future flexibility. Sorry if this is all blatantly obvious.
    Also if I wanted to test this code and create an instance of the Addressbook class, what should my code look like?
    Many thanks.
    {code}import java.util.*;
    public class Addressbook
    private static Map<Object, Object> addresses;
    public Addressbook()
    super();
    this.addresses = new TreeMap<Object, Object>();
    public static void addAddress(String name, String address)
    if (addresses.containsKey(name))
    addresses.put(name, address);
    System.out.println("Replacing " + addresses.remove(name) + " with "
    + addresses.get(name) + " for " + name);
    else
    addresses.put(name, address);
    {code}

    If you're only going to store Strings in the Map, make sure you are specifying them as generics so that all operations return Strings by default.
    You don't need to use contains if you are going to replace a map value. The old value will be returned when you place the new one in. Should be quicker, since you're not searching for the same key twice.
    Do not refer to a static variable with this. it become confusing and could result in bugs. That said use static sparingly.
    The AddressBook should probably be an instance and all the variables and methods should be instance variable and methods.
    I don't know your requirements however so I'll leave this as a suggestion.
    import java.util.*;
    public class AddressBook {
       private static Map<String, String> addresses = new TreeMap<String, String>();
       public static void addAddress(String name, String address) {
          String oldAddress = addresses.put(name, address);
          if(oldAddress != null) {
                System.out.printf("Replacing %s with %s for %s%n", oldAddress, address, name);
        public static void main(String[] args) {
            addAddress("me", "123");
            addAddress("me", "321");
    }Brushfire,

  • Need Help converting objects in a TreeMap to String

    This app counts the number of times a word occurs in a document. I used a HashMap to store the key and value. The I sorted them using TreeMap. Now I need to return the key (String) and value (Integer Object) so they may be print like this -- 'key: value'.
    Example:
    that: 3
    This mean the word 'that' appeared 3 times in the document. Below is my toString() method. TreeMap sorts everything for me but I cant return 'map' because it is not a String. So I iterated through each key and value in the map. But now I dont know how to put all the iterations into 1 String value. I would greatly appreciate any help. Code below.
    Thanks in advance.
    public String toString() {
    Object key = null;
    Object value = null;
    map = new TreeMap(map);
    Set getKeys = map.keySet();
    Iterator iterKeys = getKeys.iterator();
    while (iterKeys.hasNext()) {
    key = (String)iterKeys.next();
    value = map.get(key))
    return; // i need to return a String here
    } // end toString()
    } // end class

    I dont remember posting to the "new Java forum", but I might have. My browser locked up on me so I am not sure what happened. If I did please excuse my double post.
    Are you familar with a way to solve my problem?

  • Can  object(instance TreeMap) be inserted in a File by objectoutputstream??

    Can a object containing TreeMap instance be inserted in a File by objectoutputstream??
    class pfore{
    static class TextFile
              String category;
              String filename;
                    TreeMap filewords;
                    TextFile( )
                    {category=filename=null;
                     filewords=new TreeMap();
                    TextFile(String category,String filename,TreeMap filewords)
              this.category=category;
              this.filename=filename;
                   // this.filewords=new TreeMap();
                    this.filewords=new TreeMap(filewords);
    public static void main (String args[]){
    //creating an object of TextFile by reading a text file and also initializing it
    TextFile ob=new TextFile("dd","ff",kp);
    //kp is a created TreeMap object
    *__try{    FileOutputStream fos= new FileOutputStream("serrial.txt");__*
               *__ObjectOutputStream oos=new ObjectOutputStream(fos);__*
                *__oos.writeObject(ob);__*               
                 *__oos.flush();__*
                 *__oos.close();__*
                      *__catch(IOException e) {__*
           *__System.out.println("exception while opening the filestream"+e);__*
           *__e.printStackTrace();__*
           *__System.exit(0);__*
    }//end main
    }//end class
    Please see the underlined part because other parts are completely ok.
    it's giving exceptions like
    at.java.io.objecstreamclass invokewriteObject
    at.java.io.objectoutputstream.writeserialData
    at.java.io.objectoutputstream.writeOrdinaryObject.etc..etc

    suppose a class is a textfile in java..containing a TreeMap instance ,and two string variables as instance..
    class textfile implements Serializable
    String foo;
    String foo1;
    TreeMap t;
    textfile t=new textfile( );now how to write object t in file??
    with objectoutputstream i have tried it..bt it is throwing exceptions..
    the details i have posted in my previous Question(see above-the code)
    please give in details how to do this??

  • 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.

  • Problem with TreeMap and Vector

    Hello,
    this is the problem I have:
    I declare a Vector like this:
    Vector<String> theVector = new Vector<String>();
    I put the String needed into the Vector:
    theVector.add("blabla")
    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like this my program crash:
    theTreeMap.put(1096,theVector);
    I think I don't put the data on the good way in the TreeMap...
    Any Idea? Thank you very much

    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like
    this my program crash:
    theTreeMap.put(1096,theVector);What do you mean?

  • Problem with TreeMap

    I had a problem that I believe was similar to this posting:
    http://forum.java.sun.com/thread.jsp?forum=24&thread=200558
    although mine involves a TreeMap. I am adding approximately 250 mappings to a TreeMap, where the key is a String. Each key is unique, and, just to be sure, I analyzed the hashCode of each key, and they were also unique.
    After adding all of the mappings, however, the total size of the TreeMap is only 40! Somewhere, app. 210 mappings were overwritten. I added some debug code and found that after I added the 10th element, the size of the TreeMap did grow. Then the TreeMap would grow only on every 3rd mapping that I would add.
    The above-referenced posting mentioned that the rehashing of the map might cause it to overwrite existing values, so it made sense to set the initial capacity high enough to ensure that no rehashing occurred. Unfortunately, that posting dealt with a HashMap, which allows you to set the initial capacity. TreeMaps do not. In order to mimic this behavior, I added all of the mappings into a HashMap with an initial capacity of 250. When the HashMap was loaded, I created the TreeMap (with a unique Comparator), and then used the putAll() method of TreeMap to put the entire HashMap into the TreeMap. Voila! All 250 mappings were there.
    Nonetheless, this seems to be a very strange bug with TreeMap. Does anyone know why this happened?

    Sorry. Figured out the problem. It was all my fault (based on the comparator I was using, which caused the keys to be overwritten). how dare I accuse Sun of deploying buggy software. :)

  • Trouble with TreeMap

    Hallo everyone,
    I have as a Input CSV-like text file with a names of Decathlon athletes who have 10 diffrent results of each compitition written after each name. I made two classes, one (for the athletes) with String name and one for the Results with int points and Method that converts the times into Decathlon points. I could get all the names and the their points outputed. So it works fine. Now the trouble is that I have to put them in ascending order of their places. So I have to save them some how to compare with each other. I tried to use TreeMap for that. But can not understand how it works, cuz both key and value have to be taken from the file. Not like this example shows:
    Map textFieldMap = new HashMap();
    textFieldMap.put("1", new JTextField());
    textFieldMap.put("2", new JTextField());
    JTextField textField = (JTextField)textFieldMap.get("1");
    textField.setText("some value"); // text field associated with "1"
    but so that the loop puts the points as the key and name as value into TreeMap so at the end I could output it in ascending order. I really was trying to fix the problem but couldnt fine the solution. Can someone explain me how it works. I paste my main method code whitch outputs:
    4197 Siim Susi
    3199 Beata Kana
    3493 Jaana Lind
    3101 Anti Loop
    so hier is the code:
    I import io*, util*, lang*
    public class Decathlon {
    public static void main(String args[]) throws Exception {
    //read data from file
    File f = new File("C:\\Dokumente und Einstellungen\\RT\\IdeaProjects\\HansaDecat\\src\\10v_tulemused.txt");
    BufferedReader source =
    new BufferedReader(new FileReader(f));
    String line; //input of one line
    Results oneResult = new Results();
    Sportsmen oneSportsman = new Sportsmen();
    Time2Double timeobject = new Time2Double();
    TreeMap map = new TreeMap();
    int z=0;
    while ((line = source.readLine()) != null) {
    for (int i = 0; i <= 10; i++) {
    String[] lineUnits = line.split(";");
    if (i == 10) {  // 10th competition
    String aeg = lineUnits[10];
    StringTokenizer st = new StringTokenizer(aeg, ".");
    for (int a = 0; a < 3; a++) { //devide last result into 3 parts to convert to double
    timeobject.ConvertTime(a, Double.valueOf(st.nextToken()));
    lineUnits[10] = String.valueOf(timeobject.Time); // String.valueof(return of time)
    if(i<1){
    oneSportsman.setName(String.valueOf(lineUnits));
    }else
    oneResult.countScore(i, Double.valueOf(lineUnits[i]));
    //System.out.println(lineUnits[i] + " index" + i);
    // map.put (new Integer(z), new Data(oneResult.getName()));
    // System.out.println(z++);
    // map.put(new Results(), new Sportsmen());
    Sportsmen Sportsman = (Sportsmen)map.get(oneResult.points);
    // Sportsman.setName(oneSportsman.getName()); // text field associated with "1"
    // System.out.println("All sportsmen in Hashtable:\n" + map);
    System.out.println(oneResult.points+" "+oneSportsman.getName());
    /** ( Results elem : map.keySet() )
    System.out.println( elem ); */
    source.close();
    Thank you for Help
    Tanja

    you can use TreeSet instead of TreeMap in that use Comparable interface and override equal and compare methods

  • 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.

  • Confused about TreeMaps

    I hope someone can guide me in the right direction. I have been working on this problem for a while. I have to create an employee class with a 3 parameter constructor. From here I crete a new class that makes an array of the objects. And places them in a treemap. from the treemap, i have to print the items in the collection from a method and without a method. I have to get user input to get and remove an employee from collection. (I have to use id as key) If this is clear as mud, thats because my brain is really fuddled. Here is the code.
    public class Employee
    // Fields
    private String Name;
    private String ID;
    private double balance;
    // Three-parameter constructor
    public Employee(String n, String id, double bal)
    {          Name=n;
              ID=id;
              balance=bal;
    public void setCustomerName(String s)
              Name = s;
         public void setID(String t)
              ID = t;
         public void setBalance(double bal)
              balance = bal;
    public String getName()
    return customerName;
    public String getID()
    return acctID;
    public double getBalance()
    return balance;
    public void printBalance()
    { System.out.println("\nBalance: " + balance );  }
    public String toString()
              return "\nEmployee: " + Name + " ID: " + ID + " Balance: " + balance;
    }// end Employee class
    import java.util.*;
    import java.io.*;
    public class EmployeeMap
         public static void main(String[]args)
         Object[] accts=new Object [6];//Create array of emp objects
         accts[0]=new Employee("Smith","1",1000);
         accts[1]=new Employee("Walters","2",3000);
         accts[2]=new Emloyee("Martin","3",6000);
         accts[3]=new Employee("Mann","4",8000);
         accts[4]=new Employee("Jenkins","5",7000);
         accts[5]=new Employee("Williams","6",9000);
         Map account=new TreeMap();//create treemap
              for(int i=0; i<accts.length; i++)//add objects to treemap
              account.put("ID",accts);
         Set acctSize=account.entrySet();
         System.out.println("Object \t\t\tkey\t\tvalue");
         for(Iterator j=acctSize.iterator(); j.hasNext();)//print objects from treemap
         Map.Entry me=(Map.Entry)j.next();
         Object objKey=me.getKey();
         Object objValue=me.getValue();
         System.out.print(me +"\t");
         System.out.print(objKey+"\t");
         System.out.println(objValue);
         System.out.println("Printing Objects with a method");
         public static void printMap(String acct,Map m) //demonstrate printMap method
         Set entries=m.entrySet();
         Iterator itr=entries.iterator();
         System.out.println("Object \t\t\tkey\t\tvalue");
         while(itr.hasNext())
         Map.Entry thisPair=(Map.Entry) itr.next();
         System.out.print(thisPair.getKey() + ":");
         System.out.println(thisPair.getValue());
         public void getName (map m)//Look up object to get from user input
         System.out.println="Enter name to find";
         String inName=System.in.readline();
         while(itr.hasNext())
              account.get(inName);
         public void RemoveObject(map m)//method to remove object from treemap
         System.out.println="Enter account id to remove";
         String removeObj=System.in.readline();
         while(itr.hasNext())
              account.remove(removeObj);
    If anyone can please.....look at this and help i will be forever grateful..

    okay here is my code again
    public void setCustomerName(String s)
              Name = s;
         public void setID(String t)
              ID = t;
         public void setBalance(double bal)
              balance = bal;
        public String getName()
            return Name;
        public String getID()
            return ID;
        public double getBalance()
            return balance;
        public void printBalance()
        { System.out.println("\nBalance: " + balance );  }
        public String toString()
              return "\nEmployee: " + Name + "  ID: " + ID + "  Balance: " + balance;
    }// end class
    import java.util.*;
    public class EmployeeMap
         public static void main(String[]args)
         Object[] accts=new Object [6];//Create array of emp objects
         accts[0]=new Employee("Smith","1",1000);
         accts[1]=new Employee("Walters","2",3000);
         accts[2]=new Employee("Martin","3",6000);
         accts[3]=new Employee("Mann","4",8000);
         accts[4]=new Employee("Jenkins","5",7000);
         accts[5]=new Employee("Williams","6",9000);
         Map account=new TreeMap();//create treemap
              for(int i=0; i<accts.length; i++)//add  objects to treemap
              account.put(((Employee)accts).getID(),accts[i]);
         Set acctSize=account.entrySet();
         System.out.println("Object \t\t\tkey\t\tvalue");
         for(Iterator j=acctSize.iterator(); j.hasNext();)//print objects from treemap
         Map.Entry me=(Map.Entry)j.next();
         Object objKey=me.getKey();
         Object objValue=me.getValue();
         System.out.print(me +"\t");
         System.out.print(objKey+"\t");
         System.out.println(objValue);
         System.out.println("Printing Objects with a method");
         public void printMap(String acct,Map m) //demonstrate printMap method
         Set entries=m.entrySet();
         Iterator itr=entries.iterator();
         System.out.println("Object \t\t\tkey\t\tvalue");
              while(itr.hasNext())
              Map.Entry thisPair=(Map.Entry) itr.next();
              System.out.print(thisPair.getKey() + ":");
              System.out.println(thisPair.getValue());
         public accts get (String acct)//Look up object to get from user input
              System.out.println("Enter id to find values for:")
              String getAcct=System.in.readln();
              while(itr.hasNext())
              account.get(getAcct);
              return getAcct;
         public accts remove(String acct)//method to remove object from treemap
                   System.out.println("Enter id to remove values from map")
                   String removeObj=System.in.readln();     
                   while(itr.hasNext())
                   account.remove(removeObj);
                   return removeObj;
    I get the following errors.
    At line 40 it tells me '}' expected.
    At line 42 it says 'Statement expected'.
    At line 60 it say ; expected
    At line 68 '; 'expected
    at line 84 'class or interface declaration expected'.
    Thanks for looking at my code.

Maybe you are looking for