Converting a TreeMap to ArrayList

Hi Friends,
I have a TreeMap with some values. I want to make an ArrayList out of this which contains all the elements which are in TreeMap.
For this, I first got the keySet from TreeMap.
Using the Iterator, Iam trying to fetch the keys, and thus the values form the TreeMap.
I printed the TreeMap,, which showed me the Keys and the values which are some Objects. But when I use the getMethod of TreeMap , its returning null.
can anybody help me. Iam sure that the keys which Iam passing to get() is the right ones. as Iam printing them.

I tried entrySet, which returns Set. I used toArray on that. I got an Array of Objects. the object were of the form key=value pairs. When i printed those, It printed something like TreeMap$Entry.. I got stuck there.
Then I tried
Collection colln = treeMap.values();
Object[] objs = colln.toArray();
//Now iterate through the object array and make the ArrayList..
Finally done in a very simple way...
Thank you so much for your help...
Thanx...

Similar Messages

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

  • How to convert  from HashMap to ArrayList

    Please anybody tell me regarding how to convert hashmap to arraylist,i.e ihave two keys
    HashMap hashMap=new HashMap();
    hashMap.put("from",from);
    hashMap.put("to",to);
    My method returns an arrayList.
    Regards
    Raju..

    hi thanks for giving the information.
    My actual requirement id i have a class...
    in that i have 4 for loops..like this
    class ABC{
    ArrayList results =new ArrayList
    public ArrayList doSomeThing(MailDataForm form){
    HashMap hashMap =new HashMap();
    for(int i=i<XXX;i++){//for 1
    for(int j=0;j<XX;j++){for 2 with in for 1
    for(k=0;k<XX;k++){for 3 with in for 2{
    for(l=0;l<XX;l++){// for with in for 3
    String from=XXX;
    hashMap.put("form",from);
    for(m=0;m<XX;m++){for with in for 3
    String to=XXXX;
    hashMap.put("to",to);
    for(n=0;n<XX;n++){for with in for 3
    String subject=XXX;
    hashMap.put("subject",subject);
    }//close for 3
    }//close for 2
    }//close for 1
    // Here i have to return the ArrayList
    This is my actual requirement please help me with this
    Regards
    Raju

  • Converting Array to ArrayList not working

    Dear Members :
    Following line fails to convert my array to arraylist:
    List myArrayList = Arrays.asList(myArray);
    bcoz when I do
    System.out.println("ArrayList: "+myArrayList);
    it returns [[I@3e25a5]. The array is just a standard array: int[] myArray.
    I even tried with: List myArrayList = new ArrayList(Arrays.asList(myArray)); but same.
    Could you please suggest a solution to this ?
    Thanks in advance.
    Atanu

    YoungWinston wrote:
    Darryl Burke wrote:
    YoungWinston wrote:
    I agree, although experienced programmers would probably realize it already.Varargs existed in Java before I ever started learning it. Today for the first time, I'm beginning to understand why some programming veterans hate the feature.I think it has more to do with the <T> .... (T... array) {in the method signature. Generic types can only be references.Agreed. But it's the varargs that obscure the fact that an <tt>int[]</tt> may be treated as a single <tt>T</tt> parameter while an <tt>Object[]</tt> is treated as a <tt>T...</tt>. Which probably has something to do with the attitude of some veteran programmers to autoboxing as well.
    db

  • ArrayList indices (Phrase counter follow-up)

    Hi everybody--
    I finally figured out how to get code onto this computer I'm working with, so here's what I'm trying to do for anyone that doesn't remember. I'm using TuringPest's suggestion to go through my word list once, and then delete any index that fails on an expansion.
    This is my original post:
    I'm writing a phrase counter, and so far it's working, but I'm trying to optimize it because running over a for loop is really slowing me down.
    Here's the problem:
    I want to get phrases that repeat more than once, from length 3 words to 10 words. Each time I change the length of the phrase (say, from 10 to 9 to 8, etc down to 3), I have to run over the entire word list all over again, which eventually amounts to 8 total passes over an ArrayList that's almost 45000 elements long right now, and will get longer.
    An added complication in this is that there are certain identifiers in the word list that mark the beginnings of chapters (#) and sentences ($); any time they are hit, the iterator moves to the next word.
    So, basically, something like...
    example example example example example $ # example example example $
    ...with the repeating loop I have now would give:
    0 phrases of length 10, 9, 8, 7, or 6
    1 of length 5
    2 of length 4
    4 of length 3
    and this is the reply I'm trying to emulate:
    Find the occurences of the smaller phrases first.
    Index their locations.
    Do all subsequent longer phrase matches only from the saved locations.
    I wrote a self-contained test program, and the problem with it seems to be that the correct indices aren't being saved. The first iteration where we go through every possible index for phrases 3 words long works fine, but every subsequent one doesn't and I'm not sure why. Here's the code:
    EDIT: Sorry about the bump but I just realized I might have left something out for clarity--the newIndexes list is being created each time to hold the places where phrases can still be built, and then replacing the old indexes list (at least, that's what it's supposed to do).
    import java.util.ArrayList;
    import java.util.TreeMap;
    public class Test {
         public static void main(String[] args) {
              ArrayList<String> words = new ArrayList<String>();
                    // Two different arrays to test with
              //String[] raw = {"#", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "$", "#", "eleven", "twelve", "thirteen", "fourteen", "$"};
              String[] raw = {"#", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "$"};
              for( int i = 0; i < raw.length; i++ ) {
                   words.add( raw[i] );
              TreeMap<String, ArrayList<Integer>> phraseList = new TreeMap<String, ArrayList<Integer>>();
              ArrayList<Integer> indexes = new ArrayList<Integer>();
              int lengthOfPhrase = 3;
              for( int i = 0; i < words.size(); i++ ) {
                   indexes.add( i );
              do {
                   TreeMap<String, ArrayList<Integer>> phraseRaw = new TreeMap<String, ArrayList<Integer>>();
                   ArrayList<Integer> newIndexes = new ArrayList<Integer>();
                   int chapter = 0;
                   for( int i = 0; i < indexes.size(); i++ ) {
                        String ready = words.get( indexes.get( i ) );
                        boolean okay = true;
                        if( ready.equalsIgnoreCase( "#" ) ) {
                             okay = false;
                        } else if( !ready.equalsIgnoreCase( "$" ) ) {
                             okay = true;
                             for( int j = 0; j < lengthOfPhrase; j++ ) {
                                  if( j != 0 ) {
                                       ready = ready.concat( " " );
                                       String next = words.get( i + j );
                                       if( next.equalsIgnoreCase( "#" ) || next.equalsIgnoreCase( "$" ) ) {
                                            okay = false;
                                            break;
                                       } else {
                                            ready = ready.concat( next );
                             if( okay ) {
                                  newIndexes.add( indexes.get( i ) );
                                  if( phraseList.containsKey( ready ) ) {
                                       ArrayList<Integer> values = phraseList.get( ready );
                                       values.add( chapter );
                                       phraseList.put( ready, values );
                                  } else {
                                       if( phraseRaw.containsKey( ready ) ) {
                                            ArrayList<Integer> values = phraseRaw.get( ready );
                                            values.add( chapter );
                                            phraseList.put( ready, values );
                                       } else {
                                            ArrayList<Integer> newValues = new ArrayList<Integer>();
                                            newValues.add( chapter );
                                            phraseRaw.put( ready, newValues );
                   lengthOfPhrase++;
                   indexes.clear();
                   indexes = newIndexes;
              } while( lengthOfPhrase <= 10 );
    }Does anyone see where I'm going wrong?
    Thanks,
    Jezzica85
    Message was edited by:
    jezzica85

    OK, I guess I'll try again to explain what's going on and try to be more clear.
    Inside the map, there is a list of phrases, ranging from 3 to 20 words in length. For those phrases that appear in the document more than once (that is, the length of their arrayList value is 2 or more), I need to know if they are contained within any other phrase keys in the map.
    So, if part of the map was like this:
    This is an example=[2,4,6]
    This is an=[2,4,6]
    is another example of this=[1,3,5]
    is another example=[1,3,5]
    The revised map after the substrings were taken out would be:
    This is an example=[2,4,6]
    is another example of this=[1,3,5]
    The second entry of the original map would be taken out because it was contained by and occurred in the same positions as the first, and the fourth entry of the original map would be taken out because it was contained by and occurred in the same positions as the third.
    Is this any clearer?
    Thanks for looking and trying to help,
    Jezzica85

  • A Map and ArrayList problem

    Hi all,
    I have a TreeMap that has a string as a key and an ArrayList of Integers as a value. What I'd like to do is get each of the ArrayLists, then determine for each ArrayList where the first nonzero entry is. Once I do that, I want to lump them together, so all the arrayLists with a similar first nonzero value are together. I've been working on it, and I've got my solution partially working, but at the moment for the rest I'm stumped. Here's my code, can anyone help me out?
    Thanks,
    Jezzica85
    // "chapters" is the number of indices in the ArrayList value of FrequencyTable, minus one (the last is a sum).
    // ex. one entry of the frequencyTable is:
    //     example=[0, 1, 2, 4, 7], the last index is the sum of all the others
    public void getStartingPoints( int chapters ) {
         // frequencyTable = TreeMap<String, ArrayList<Integer>>
         // This has been fully created by the time this method is called.
         // In this example, "chapters" would be 4
         for( int i = 0; i < chapters; i++ ) {
              TreeSet<String> newWords = new TreeSet<String>();
              Iterator iterator = frequencyTable.entrySet().iterator();
              while( iterator.hasNext() ) {
                   (Map.Entry) current = (Map.Entry)iterator.next();
                   String key = (String)current.getKey();
                   ArrayList<Integer> value = (ArrayList<Integer>)current.getValue();
                   // If we're dealing with the first index in the arrayList -- this part works.
                   if( i == 0 && value.get( 0 ) > 0 ) {
                        newWords.add( key );
                   // If we're dealing with any other index -- this doesn't work.
                   // What I want to do is see if all the indices from 0 to i - 1 add up to 0.
                   if( i > 0 ) {
                        int sum = 0;
                        for( int j = 0; j < i; j++ ) {
                             sum = sum + value.get( j );
                        if( sum == 0 ) {
                             newWords.add( key );
                   

    Read, re-read, then re-read your post. Couldn't understand it.
    Please explain more:
    1- You have:frequencyTable = TreeMap<String, ArrayList<Integer>>That seems to be your input structure, right?
    So what is supposed to be your resulting structure?
    A big ArrayList that will hold all integers?
    A big Set that will hold whatever?
    Else?
    2- The other input seems to be an int named chapters.
    What is the relation between this number and the frequencyTable structure?
    3- In that frequencyTable the ArrayLists contain integers.
    Are those integers the indices you are referring?
    Are those integers allways sorted in your ArrayLists?
    Are there allways at least one zero integer in your ArrayLists?

  • OBIEE - Using Multiple Select Rows In Grid As Parameters

    Hello All,
    First post from an OBI Newbie. I am getting used to creating dashboards and have got my head around drilling with values, but I have a user requirement that I am not sure is possible.
    A standard query returns the following datagrid information ("," = column divider):
    Product Id, Product Description, Colour, Total Sales
    1, Chair, Red, 4
    2, Chair, Blue, 3
    3, Chair, Black, 5
    I know that I can enable a drill on a specific colour to give a datagrid such as (if Red Selected):
    Order Reference, Product Id, Product Description, Colour, Units
    687678657, 1, Chair, Red, 3
    687678658, 1, Chair, Red, 1
    The user requirement is to select multiple rows (possible by holding Ctrl) and to then effectively "drill" with the multiple selected values. Eg Red, Blue:
    Order Reference, Product Id, Product Description, Colour, Units
    687678657, 1, Chair, Red, 3
    687678658, 1, Chair, Red, 1
    687678660, 2, Chair, Blue, 3
    I presume that a separate report will be required, but I am not sure how to trigger and/or pass the multiple product id's. Can anyone help with a solution?
    Edited by: 885689 on 16-Sep-2011 06:27

    I got this working by changing the signature of the Application Module method to use ArrayList rather than String[], then you can marshal the Struts FormBean contents into an ArrayList to pass up.
    To do this, subclass the DataAction by using "Go To Code" off of the context menu and then override the initializeMethodParameters() method:
      protected void initializeMethodParameters(DataActionContext actionContext, JUCtrlActionBinding actionBinding)
        //Get the String Array from the Form Bean
        String[] selection = (String[])((DynaActionForm)actionContext.getActionForm()).get("multiSelect");
        //convert that to an ArrayList
        ArrayList selectionArr = new ArrayList( Arrays.asList(selection));
        //Add that object to the Arg List for the AM method
        ArrayList params = new ArrayList();
        params.add(selectionArr);
        actionBinding.setParams(params);
      }

  • Using multiple select lists in ADF

    Hi,
    I am trying to use a multiple select list in my JSP page, and have a method in the ApplicationModule be called when the Struts action is called. I am following the example ADF tutorials, where the method is added to the ApplicationModule class, then dragged onto the Stuts Flow diagram (to associate it with an action).
    I am able to create a dyna form bean for the page that contains the multi select as a type "java.lang.String[]" (string array). I am able get that values that were selected in a normal action's "execute" method. For example:
    msf = (DynaActionForm) form;
    String[] statusSelection = (String[]) msf.get("multSelectList");
    However, I cannot seem to get the "multSelectList" values into a method in my Application Module class. The "multSelectList" is defined in my dynaFormBean as a String[] type. I am passing it in as an argument like the following....
    public void setParams(String multSelectList[]) {
    This results in the method not being called at all. I am not sure why. Does this have something to do with a String[] not being serializable??
    However, if I just attempt to pass other types form items to the method, it works. For example:
    public void setParams(String simpleCheckbox) {
    Does anyone know how to use multiple select lists in conjunction with ADF?
    P.S.
    my multSelectList looks something like this:
    <select name="multSelectList" multiple size="5">
    <option value="ALL">Select All</option>
    <option value="preferred">Preferred</option>
    <option value="standard">Standard</option>
    <option value="approved">Approved</option>
    <option value="interim">Interim</option>
    </select>

    I got this working by changing the signature of the Application Module method to use ArrayList rather than String[], then you can marshal the Struts FormBean contents into an ArrayList to pass up.
    To do this, subclass the DataAction by using "Go To Code" off of the context menu and then override the initializeMethodParameters() method:
      protected void initializeMethodParameters(DataActionContext actionContext, JUCtrlActionBinding actionBinding)
        //Get the String Array from the Form Bean
        String[] selection = (String[])((DynaActionForm)actionContext.getActionForm()).get("multiSelect");
        //convert that to an ArrayList
        ArrayList selectionArr = new ArrayList( Arrays.asList(selection));
        //Add that object to the Arg List for the AM method
        ArrayList params = new ArrayList();
        params.add(selectionArr);
        actionBinding.setParams(params);
      }

  • TreeSelectionListener with JPanel is not reacting

    Hi all!
    I have class which extends JPanel, and is later docked in a side menu. The effect should be like the Tools menu in VisualStudio.
    Inside the JPanel I have a JTree. And the TreeSelectionListener isn't working. I tried the JTree code in a plain project and it works. So I figure it's something to do with the JPanel.
    Here my code with the JTree
    package de.lmu.ifi.pst.swep.rid.gui;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.Map;
    import java.util.TreeMap;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import com.vlsolutions.swing.docking.DockKey;
    import com.vlsolutions.swing.docking.Dockable;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.AbstractCartridgeElement;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.AbstractModelElement;
    import de.lmu.ifi.pst.swep.rid.cartridgeInterface.ICartridge;
    import de.lmu.ifi.pst.swep.rid.cartridgeloader.CartridgeLoader;
    import de.lmu.ifi.pst.swep.rid.cartridgeloader.ComponentLoader;
    import de.lmu.ifi.pst.swep.rid.interfaces.ICartridgeBay;
    import de.lmu.ifi.pst.swep.rid.utils.IconProvider;
    import de.lmu.ifi.pst.swep.rid.utils.Settings;
    import de.lmu.ifi.pst.swep.rid.utils.IconProvider.Identifier;
    * The toolbar for selecting canvas tools, such as select and new Cartridge
    * Element creation.
    public class CartridgeToolbar extends JPanel implements Dockable, ICartridgeBay {
         static {
              Settings.register("cartridge.selection.none", false);
              Settings.register("cartridge.selection.default", true);
              Settings.register("cartridge.selection.user", false);
              Settings.register("cartridge.selection.xul", true);
              Settings.register("cartridge.selection.uml", true);
         private static final long serialVersionUID = 8926943523499013449L;
         private DockKey dockKey = new DockKey("cartridgeToolbar", "Tools", null, IconProvider
                   .getSmallImage(Identifier.VIEW_TOOLS));
         private Map<String, ArrayList<AbstractCartridgeElement>> cartridgeGroups = new TreeMap<String, ArrayList<AbstractCartridgeElement>>();
         private JTree cartridgeTree;
         public CartridgeToolbar(ComponentLoader componentLoader) {
              super();
              dockKey.setFloatEnabled(true);
              dockKey.setMaximizeEnabled(false);
              dockKey.setResizeWeight(0.1f);          
              this.setLayout(new BorderLayout());          
              setPreferredSize(new Dimension(200, 600));
              cartridgeTree = new JTree(new DefaultMutableTreeNode("Unpainted tree"));
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                 renderer.setOpenIcon(null);
                 renderer.setClosedIcon(null);
                 renderer.setLeafIcon(null);
                 cartridgeTree.setCellRenderer(renderer);
              cartridgeTree.putClientProperty("JTree.lineStyle", "None");
              DefaultTreeSelectionModel selectionModel = new DefaultTreeSelectionModel();
                 selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
              cartridgeTree.setSelectionModel(selectionModel);
              fillTreeWith("cartridgexul.xml");
              fillTreeWith("cartridgeuml.xml");
              cartridgeTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {//FIXME: listener not working
                   @Override
                   public synchronized void valueChanged(TreeSelectionEvent e) {
                      DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
                      System.out.println("You selected " + node);
              cartridgeTree.putClientProperty("JTree.lineStyle", "None");
              cartridgeTree.setSelectionModel(null);
              JScrollPane scrollPane = new JScrollPane(cartridgeTree);
              this.add(scrollPane, BorderLayout.CENTER);
          * Method returns the name of the currently selected Cartridge Element that is to be drawn on the canvas
          * @return
          *           Name of the selected cartridge element.
         public String getSelectedElement()
            //TODO: if inner node
              return cartridgeTree.getLastSelectedPathComponent().toString();          
         private void fillTreeWith(String cartrigdeFileName)
              File dir = new File(".");
              String rootPath;
              try {
                   rootPath = dir.getCanonicalPath() + File.separator + "resources";
                   addCartridge(rootPath, cartrigdeFileName);
              } catch (IOException e) {
                   e.printStackTrace();
         public void addCartridge(String rootPath, String cartrigdeFileName) {
              CartridgeLoader catridgeLoader = new CartridgeLoader(rootPath, cartrigdeFileName);
              ICartridge cartridgeInterface = catridgeLoader.loadCartridge();
              final String nameCartridge = cartridgeInterface.getCartridgeName();
              ArrayList<AbstractCartridgeElement> catridgeGroupElements = generateFactories(cartridgeInterface);
              DefaultMutableTreeNode root = (DefaultMutableTreeNode) cartridgeTree.getModel().getRoot();
              DefaultMutableTreeNode cartridgeGroupNode= new DefaultMutableTreeNode(nameCartridge);
              DefaultMutableTreeNode elementNode ;
              DefaultMutableTreeNode subElementNode;
              for (AbstractCartridgeElement element : catridgeGroupElements) {
                   elementNode = new DefaultMutableTreeNode(element.getElementName());//TODO: add icon
                   subElementNode = new DefaultMutableTreeNode(element.getElementName() + "1");
                   elementNode.add(subElementNode);
                   subElementNode = new DefaultMutableTreeNode(element.getElementName() + "2");
                   elementNode.add(subElementNode);
                      cartridgeGroupNode.add(elementNode);//TODO: add subType          
              root.add(cartridgeGroupNode);
              cartridgeGroups.put(cartridgeInterface.getCartridgeName(), catridgeGroupElements);
          * With getting a new cartridge interface the method will be able to create
          * all factories of the cartridge interface. Element factories are used to
          * add new elements to the canvas.
          * @return List of factories belonging to a cartridge interface
         private ArrayList<AbstractCartridgeElement> generateFactories(ICartridge cartridgeInterface) {
              ArrayList<AbstractCartridgeElement> cartridgeGroupElements = new ArrayList<AbstractCartridgeElement>();
              for (Enumeration<Integer> el = cartridgeInterface.getElementIDs(); el.hasMoreElements();) {
                   cartridgeGroupElements.add(cartridgeInterface.getElementFactoryByID((Integer) el.nextElement()));
              return cartridgeGroupElements;
         @Override
         public DockKey getDockKey() {
              return dockKey;
         @Override
         public AbstractModelElement createCartridgeElement(String id) {
              // getElementFactoryByID
              return null;
         @Override
         public Component getComponent() {
              // TODO Auto-generated method stub
              return null;
         @Override
         public JComponent getComponent(String path, String cartridgeName) {
              // TODO Auto-generated method stub
              return null;
         @Override
         public void setButtonGroup(ButtonGroup buttongroup) {
              // TODO Auto-generated method stub
    }The most important is ofcourse the constructor. Any suggestions and help would be greatly apprieciated.
    best of all,
    Szymon

    cartridgeTree.setSelectionModel(null);You creating a new selection model, add it to the tree and add a listener to it. Then you throw it away.

  • Including databases in Java

    Hello people,
    I have a question for including data bases in Java:
    Could I import a DBASE-data base in Java ?
    My intention is to import DBASE - datas, and then convert them into
    a ArrayList with a function,in wich they are nested.
    I hope anyone can do anything with it.
    Bye and greetings
    Manuel

    If you're using windows then you can go to the control panel ---> click on ODBC and you will find DBase is there.

  • My java application runs quite slowly.

    My application is just for creating a data structure(like map<double,link<Object>>) and then search in the it and delete some element or add some,
    the application reads data from a file, and every 5000 lines, it will compute once, and here is the finish time of each roll:(ms)
    94
    187
    234
    297
    344
    11828
    22354
    32761
    obviously, after five rolls, the application becomes slower, and after that keep going in the slow speed.
    in each roll the overhead of computing should be the same
    I just do not get the idea why it becomes slow.

    private BuyBook buyBook = new BuyBook();
         private SellBook sellBook = new SellBook();
         TreeMap<Double,ArrayList<IOrderEntity>>tmpSellBook;
         IOrderEntity tmpSellOE;
         IOrderEntity tmpBuyOE ;
         IOrderEntity tmp;
         Double buyPrice;
         Double sellPrice;
         ReversedTreeMap<Double,ArrayList<IOrderEntity>>tmpBuyBook;
         Iterator it1;
         Iterator it2;
    public /*synchronized*/ void synchronizeBooks(IOrder o){
                   if(o.getType()==1){
                        if(((LimitOrderEntity)o).isBuy()){
                             getBuyBook().sync((LimitOrderEntity)o);
                        }else{
                             getSellBook().sync((LimitOrderEntity)o);
                   }else if(o.getType()==3){
                        getSellBook().update((CancelLimitOrderEntity)o);
                        getBuyBook().update((CancelLimitOrderEntity)o);
                   }else{
                        println("illegal param"+o);
    public void exchange(IOrderEntity order) {
              if(order.getType()==2){
                   while(order!=null){
                        if(order.isBuy()){
                             sellPrice = findProperOrderInSell(order);
                             if(sellPrice.isNaN()||getSellBook().getSellList().get(order.getSymbol()).isEmpty())
                                  return;
                             tmpSellBook = getSellBook().getSellList().get(order.getSymbol());
                             tmpSellOE = (IOrderEntity)tmpSellBook.get(sellPrice).get(0)/*firstEntry().getValue()*/;
                             if(order.getQuantity().intValue()>tmpSellOE.getQuantity().intValue()){
                                  order.setQuantity(order.getQuantity()-tmpSellOE.getQuantity());
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpSellOE.getOrderId()+" on "+tmpSellOE.getQuantity()+" shares at price "+tmpSellOE.getPrice());
                                  it1 = tmpSellBook.get(sellPrice).iterator();
                                  if(it1.hasNext()/*&&it1.next()!=null*/){
                                       it1.next();
                                       it1.remove();
                                       if(tmpSellBook.get(sellPrice).isEmpty()){
                                            Iterator it2 = tmpSellBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                             }else if(order.getQuantity().intValue()==tmpSellOE.getQuantity().intValue()){
                                  //order.setQuantity(order.getQuantity()-tmpSellOE.getQuantity());
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpSellOE.getOrderId()+" on "+tmpSellOE.getQuantity()+" shares at price "+tmpSellOE.getPrice());
                                  it1 = tmpSellBook.get(sellPrice).iterator();
                                  if(it1.hasNext()/*&&it1.next()!=null*/){
                                       it1.next();
                                       it1.remove();
                                       if(tmpSellBook.get(sellPrice).isEmpty()){
                                            it2 = tmpSellBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                                  return;
                             }else{
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpSellOE.getOrderId()+" on "+order.getQuantity()+" shares at price "+tmpSellOE.getPrice());
                                  tmp = tmpSellBook.get(sellPrice).get(0);
                                  tmp.setQuantity(tmpSellBook.get(sellPrice).get(0).getQuantity()-order.getQuantity());
                                  /*tmp.setTime(order.getTime());
                                  Iterator it1 = tmpSellBook.get(sellPrice).iterator();
                                  if(it1.hasNext()&&it1.next()!=null){
                                       it1.next();
                                       it1.remove();
                                       if(tmpSellBook.get(sellPrice).isEmpty()){
                                            Iterator it2 = tmpSellBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                                  synchronizeBooks(tmp);*/
                                  return;
                        }else{
                             buyPrice = findProperOrderInBuy(order);
                             if(buyPrice.isNaN()||getBuyBook().getBuyList().get(order.getSymbol()).isEmpty())
                                  return;
                             tmpBuyBook = getBuyBook().getBuyList().get(order.getSymbol());
                             tmpBuyOE = (IOrderEntity)tmpBuyBook.get(buyPrice).get(0)/*firstEntry().getValue()*/;
                             if(order.getQuantity().intValue()>tmpBuyOE.getQuantity().intValue()){
                                  order.setQuantity(order.getQuantity()-tmpBuyOE.getQuantity());
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpBuyOE.getOrderId()+" on "+tmpBuyOE.getQuantity()+" shares at price "+tmpBuyOE.getPrice());
                                  it1 = tmpBuyBook.get(buyPrice).iterator();
                                  if(it1.hasNext()/*&&it1.next()!=null*/){
                                       it1.next();
                                       it1.remove();
                                       if(tmpBuyBook.get(buyPrice).isEmpty()){
                                            it2 = tmpBuyBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                             }else if(order.getQuantity().intValue()==tmpBuyOE.getQuantity().intValue()){
                                  //order.setQuantity(order.getQuantity()-tmpSellOE.getQuantity());
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpBuyOE.getOrderId()+" on "+tmpBuyOE.getQuantity()+" shares at price "+tmpBuyOE.getPrice());
                                  it1 = tmpBuyBook.get(buyPrice).iterator();
                                  if(it1.hasNext()/*&&it1.next()!=null*/){
                                       it1.next();
                                       it1.remove();
                                       if(tmpBuyBook.get(buyPrice).isEmpty()){
                                            it2 = tmpBuyBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                                  return;
                             }else{
                                  println("transaction of "+order.getSymbol()+" :"+order.getOrderId()+" with "+tmpBuyOE.getOrderId()+" on "+order.getQuantity()+" shares at price "+tmpBuyOE.getPrice());
                                  tmp = tmpBuyBook.get(buyPrice).get(0);
                                  tmp.setQuantity(tmpBuyBook.get(buyPrice).get(0).getQuantity()-order.getQuantity());
                                  /*tmp.setTime(order.getTime());
                                  Iterator it1 = tmpBuyBook.get(buyPrice).iterator();
                                  if(it1.hasNext()&&it1.next()!=null){
                                       it1.next();
                                       it1.remove();
                                       if(tmpBuyBook.get(buyPrice).isEmpty()){
                                            Iterator it2 = tmpBuyBook.entrySet().iterator();
                                            it2.next();
                                            it2.remove();
                                  synchronizeBooks(tmp);*/
                                  return;
    public Double findProperOrderInBuy(IOrderEntity order){
              if(getBuyBook().getBuyList()!=null&&!getBuyBook().getBuyList().isEmpty()){
                   tmpBuyBook = getBuyBook().getBuyList().get(order.getSymbol());
                   if(tmpBuyBook!=null&&!tmpBuyBook.isEmpty()){
                        return tmpBuyBook.firstKey();
              return Double.NaN;
          * find a proper price for a sell order
          * @param order
          * @return the price, if NaN, means no proper price
         public Double findProperOrderInSell(IOrderEntity order){
              if(getSellBook().getSellList()!=null&&!getSellBook().getSellList().isEmpty()){
                   tmpSellBook = getSellBook().getSellList().get(order.getSymbol());
                   if(tmpSellBook!=null&&!tmpSellBook.isEmpty()){
                        return tmpSellBook.firstKey();
              return Double.NaN;
    .......this is buybook
    private Map<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>> buyList =
              new HashMap<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>>();
         Iterator it1;Object test1;Iterator it2;Object test2;Iterator it3;Object test3;IOrderEntity tmp;
          * get the buybook in a map
          * @return the map
         public Map<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>> getBuyList() {
              return buyList;
          * set the buybook
          * @param buyList
         public void setBuyList(Map<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>> buyList) {
              this.buyList = buyList;
          * synchronize the list with a list of IOrderEntity
          * @param loe: the list
         public void sync(List<IOrderEntity> loe){
              for(IOrderEntity x:loe){
                   sync(x);
          * synchronize the with an IOrderEntity object
          * @param x the IOrderEntity
         public void sync(IOrderEntity x){
              if(x.getSymbol()!=null&&x.getQuantity()>0&&x.getTime()>=0){
                   //if the entity is well-formated
                   if(getBuyList().containsKey(x.getSymbol())){
                        //if the symbol exist in list already
                        if(getBuyList().get(x.getSymbol()).containsKey(x.getPrice())){
                             //if the price has been there
                             getBuyList().get(x.getSymbol()).get(x.getPrice()).add(/*put(x.getTime(), */x);
                        }else{
                             //else the price is new
                             ArrayList<IOrderEntity> tmpTreeMap1 = new ArrayList<IOrderEntity>();
                             tmpTreeMap1.clear();
                             tmpTreeMap1.add(/*put(x.getTime(), */x);
                             getBuyList().get(x.getSymbol()).put(x.getPrice(), tmpTreeMap1);
                   else{
                        ReversedTreeMap<Double,ArrayList<IOrderEntity>> tmpTreeMap2 = new ReversedTreeMap<Double,ArrayList<IOrderEntity>>();
                        //else the symbol is new
                        ArrayList<IOrderEntity> tmpTreeMap1 = new ArrayList<IOrderEntity>();
                        tmpTreeMap2.clear();
                        tmpTreeMap1.clear();
                        tmpTreeMap1.add(/*put(x.getTime(), */x);
                        tmpTreeMap2.put(x.getPrice(), tmpTreeMap1);
                        getBuyList().put(x.getSymbol(), tmpTreeMap2);
          * update the book with a cancelListmitorderenetity
          * @param cloe:cancellimitorderentity
         public void update(CancelLimitOrderEntity cloe){
              it1 = getBuyList().entrySet().iterator();
              test1 = null;
              while(it1.hasNext()&&(test1 = it1.next())!=null){
                   it2 = ((Map.Entry<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>>)test1).getValue().entrySet().iterator();
                   test2 = null;
                   while(it2.hasNext()&&(test2 = it2.next())!=null){
                        it3 = ((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue().iterator();
                        test3 = null;
                        while(it3.hasNext()&&(test3 = it3.next())!=null){
                             tmp = ((IOrderEntity)test3);
                             if(cloe.getOrderId().equals(tmp.getOrderId())){
                                  if(cloe.getQuantity().intValue()<tmp.getQuantity().intValue()){
                                       tmp.setQuantity(tmp.getQuantity()-cloe.getQuantity());
                                       tmp.setTime(cloe.getTime());
                                       //delete
                                       it3.remove();
                                       //add
                                       ((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue().add(tmp);
                                       return;
                                  }else if(cloe.getQuantity().intValue() == tmp.getQuantity().intValue()){
                                       it3.remove();
                                       if(((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue().isEmpty()){
                                            it2.remove();
                                            if(((Map.Entry<String,ReversedTreeMap<Double,ArrayList<IOrderEntity>>>)test1).getValue().isEmpty()){
                                                 it1.remove();
                                       return;
                                  }else{
                                       //System.out.println(cloe.getOrderId()+":cancel quantity>current quantity.");
                                       return;
    ....and this is sell book
    private Map<String,TreeMap<Double,ArrayList<IOrderEntity>>> sellList =
              new HashMap<String,TreeMap<Double,ArrayList<IOrderEntity>>>();
         Iterator it1;Object test1;Iterator it2;Object test2;Iterator it3;Object test3;IOrderEntity tmp;
          * get the buybook in a map
          * @return the map
         public Map<String,TreeMap<Double,ArrayList<IOrderEntity>>> getSellList() {
              return sellList;
          * set the buybook
          * @param buyList
         public void setSellList(Map<String,TreeMap<Double,ArrayList<IOrderEntity>>> sellList) {
              this.sellList = sellList;
          * synchronize the list with a list of IOrderEntity
          * @param loe: the list
         public void sync(List<IOrderEntity> loe){
              for(IOrderEntity x:loe){
                   sync(x);
          * synchronize the with an IOrderEntity object
          * @param x the IOrderEntity
         public void sync(IOrderEntity x){
              ArrayList<IOrderEntity> tmpTreeMap1 = new ArrayList<IOrderEntity>();
              TreeMap<Double,ArrayList<IOrderEntity>> tmpTreeMap2 = new TreeMap<Double,ArrayList<IOrderEntity>>();
              if(x.getSymbol()!=null&&x.getQuantity()>0&&x.getTime()>=0){
                   //if the entity is well-formated
                   if(getSellList().containsKey(x.getSymbol())){
                        //if the symbol exist in list already
                        if(getSellList().get(x.getSymbol()).containsKey(x.getPrice())){
                             //if the price has been there
                             getSellList().get(x.getSymbol()).get(x.getPrice()).add(/*put(x.getTime(), */x);
                        }else{
                             //else the price is new
                             tmpTreeMap1.clear();
                             tmpTreeMap1.add(/*put(x.getTime(), */x);
                             getSellList().get(x.getSymbol()).put(x.getPrice(), tmpTreeMap1);
                   else{
                        //else the symbol is new
                        tmpTreeMap2.clear();
                        tmpTreeMap1.clear();
                        tmpTreeMap1.add(/*put(x.getTime(), */x);
                        tmpTreeMap2.put(x.getPrice(), tmpTreeMap1);
                        getSellList().put(x.getSymbol(), tmpTreeMap2);
          * update the book with a cancelListmitorderenetity
          * @param cloe:cancellimitorderentity
         public void update(CancelLimitOrderEntity cloe){
              it1 = getSellList().entrySet().iterator();
              test1 = null;
              while(it1.hasNext()&&(test1 = it1.next())!=null){
                   it2 = ((Map.Entry<String,TreeMap<Double,ArrayList<IOrderEntity>>>)test1).getValue().entrySet().iterator();
                   test2 = null;
                   while(it2.hasNext()&&(test2 = it2.next())!=null){
                        it3 = ((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue()./*entrySet().*/iterator();
                        test3 = null;
                        while(it3.hasNext()&&(test3 = it3.next())!=null){
                             tmp = ((/*Map.Entry<Long, */IOrderEntity/*>*/)test3)/*.getValue()*/;
                             if(cloe.getOrderId().equals(tmp.getOrderId())){
                                  if(cloe.getQuantity().intValue()<tmp.getQuantity().intValue()){
                                       tmp.setQuantity(tmp.getQuantity()-cloe.getQuantity());
                                       tmp.setTime(cloe.getTime());
                                       //delete
                                       it3.remove();
                                       //add
                                       ((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue().add(tmp);
                                       return;
                                  }else if(cloe.getQuantity().intValue() == tmp.getQuantity().intValue()){
                                       it3.remove();
                                       if(((Map.Entry<Double,ArrayList<IOrderEntity>>)test2).getValue().isEmpty()){
                                            it2.remove();
                                            if(((Map.Entry<String,TreeMap<Double,ArrayList<IOrderEntity>>>)test1).getValue().isEmpty()){
                                                 it1.remove();
                                       return;
                                  }else{
                                       //System.out.println(cloe.getOrderId()+": cancel quantity>current quantity.");
                                       return;
         }here is how the application start
    AbstractExchangeDelegate ed3 = new ExchangeDelegate("largetest");
                   input = zipFile.getInputStream(entry);
                   IStockDataSource sdsd1 = new StockDataSourceDelegate(input);
                   if(sdsd1!=null){
                        int counter = 0;
                        //ed.sychronizeBooks(sdsd.getAllOrderEntityAsList(), sdsd.getCancelLimitOrderEntityList());
                        for(IOrder x:sdsd1.getAllOrderEntityAsList()){
                             if(!(x.getType()==2))
                                  ed3.synchronizeBooks(x);
                             else{
                                  ed3.exchange((MarketOrderEntity)x);
                                  counter++;
                        if(counter>5000){
                             System.gc();
                   }

  • Problem with LinkedList Creation

    Hello,
    I am trying to convert from using an arraylist to a linkedlist for my project because I need add and remove elements. When I create a new linkedlist, I get this error:
    //create a new linkedlist object
    LinkedList sizeList = new LinkedList();
    Error:
    "LinkedList is a raw type. References to generic type LinkedList<E> should be parameterized."Currently, my arraylist is used this way:
         TextArea roomDisplay[] = new TextArea[16]; In my frame, I have 16 text areas. For each index in that array, I have different texts, but since arraylists are unsuitable for insertions and deletions, I need to convert this collection type to a linkedlist, and I am kind of lost right now.
    I know for a linkedlist, in order to add text, I need to switch to the add() method rather than setText() method as I currently do right now using arraylist.
    Please guide me on how to do this conversion.Thanks.

    This helps a lot. I also read the pdf file posted at the link you provided, but am new to this.
    So now I am trying to add the first (as a test) element to one of my panels in my frame:
              sizeList.add(new TextArea("test"));
              roomPanel.add(List<TextArea>(sizeList));the first line compiled ok, but there's a problem with the second one. I guess my parameter's wrong or the code is just way off. The error is: "List cannot be resolved. TextArea cannot be resolved."
    I also tried this statement:
    roomPanel.add(sizeList);And got error: The method add(Component) in the type Container is not applicable to the argument (List<TextArea>).
    I don't understand why it won't take it.

  • Selecting Against An Array

    Hello Yall, I am having a baffling problem and it is really ticking me off. Perhaps one of you can help me. I am receiving a java.util.ArrayList of IDs, I then want to used these IDs to do a SELECT against sql server. Is there a way of converting my java.util.ArrayList to a java.sql.Array, I try to convert it into array first and then to a java.sql.Array, it errors on me like crazy. If anyone knows, then please clue me in on how to do this??????????? Of course, I can get each value individually and make a new java.sql.Array, but then that is inefficient and I might as well do my selects against the DB one by one anyways.
    If no one knows how to do this, I am also open to suggesstions on how I can make the preparedStatement take my array some other way. setObject is not working with my Driver for some reason. I am WebSphere and Merant SQl.
    Thank You For Any Help.

    what about creating a SELECT with a nested SELECT?StringBuffer sb = new StringBuffer("SELECT foo FROM bar WHERE fooId in ( ");
    List strings = getArrayList();
    Iterator iter = strings.iterator();
    while ( iter.hasNext() ) {
      sb.append( '\'' );
      sb.append( iter.next() );
      sb.append( '\'' );
      if ( iter.hasNext() ) {
        sb.append( ", " );
    sb.append(" )");
    Statement stmt = getConnection().createStatement( sb.toString() );
    // ...robert

  • How can I convert  an ArrayList to a String[]

    Hi,
    How can I convert an ArrayList (only with strings) to a String[] ?
    I've tried this :
         public static String listToString(List l) {
              StringBuffer sb = new StringBuffer();
              Iterator iter = l.iterator();
              while (iter.hasNext()) {
                   sb.append(iter.next().toString());
                   if (iter.hasNext()) {
                        sb.append(',');
              return sb.toString();
    But what I get is an array of xxxxx@435634 (for example).
    Thanks a lot !

    Strings are Objects but not all Objects are Strings and at least one of the elements in your List is not a String.

  • How do I convert an arrayList to an array []

    I want to create a generic method that I can pass a Collection ( An ArrayList if I have to be specific ) and also tell this method the underlying Object type the Collection contains and have it call the Collections.toArray method and create an array [] of the type I specify.
    Part of the problem is how do I have the method resolve the return type at run time and how do I use the Class variable to tell it the type of objects the Collection holds.
    Fo instance I load an ArrayList with 3 MyClass objects.
    I want to pass this to the method and have it return me an array of Type MyClass containing 3 items.
    I don't want to have to be tied to a method with the signature
    public MyClass [] convert( ArrayList myList  ){ ... }Thanks ...

    Since it is an "old system" I doubt that is feasible. Also I believe that this was intentionally left out of the API because specifying the array type is more natural than the Class object and using the normal approach you get back the same zero-length array that you passed in if the collection is of size zero. It does look nice from a "caller" perspective though.

Maybe you are looking for

  • BIP Trial 11.1.1..6: Error while generating XML data in Data Model

    Hello, I have created a Data Model with a single query. After saving the DM and clicking on the XML icon to generate sample data, I get the following error: The XML page cannot be displayed Cannot view XML input using XSL style sheet. Please correct

  • Clear block not working !! help required asap

    We have used clearblock all inside a fix command, it used to work before and when we migrated over to new server it is failing to work. It is not throwing out an error but it is not clearing. I checked the difference at the database level and found t

  • My new phone is an Orange Rio 11, when its arrived it has an EE sim.

    I had an old nokia phone on the Orange network as where i live we only have the Orange signal.I have put the sim in the phone but it keeps telling me to insert the sim.Is ee and Orange all the same now, im confused.Plus i cant set the date and time a

  • Calling a DLL from LabVIEW causes crash

    Okay, this is an odd one. I have searched through various posts and have found several things that were close but not quite the same. I have a DLL. I pass to the function in the DLL two strings, each one representing an absolute path to a pair of fil

  • External harddrive won't shut down in Mavericks

    Hi all, I have an external hard drive from which I boot OS X Mavericks on my iMac late 2007. In all previous OS X versions, the harddrive would shut down whenever I put my iMac to sleep. Now with Mavericks it won't anymore. It will constantly spin wh