Sort() function used in HashMap, ArrayList or Collections?

I need some testing codes for similar function like sort() for HashMap, Arraylist or Collection objects.
Thanks in advance for help!

http://developer.java.sun.com/developer/TechTips/1998/tt0421.html#tip1
take a look at this link

Similar Messages

  • Sort functionality using MULTIPLE columns in a table control

    Hi all,
    I have a custom screen with table control.Now i need to provide SORT functinality in this screen for the columns in the table control.
    My questins:
    1.Is it possible to seelct MULTIPLE columns in a table control for SORTING?If yes,what explicit settings do i need to do while creatng the TABEL CONTROL in the screen?DO I need to select "Column selection " as MULTIPLE??
    2.How do I write the code for SORT functinonality for multiple columns?
    I know how to write the code for SORTING on basis of single column .
    Thanks!

    Hi Rob,
    Thanks for the reply.
    However I was thinking to apply the same logic as for single columns as follows:
    types : begin of ty_fields,
                c_fieldname(20),
               end of ty_fields.
    data  : t_fields type table of ty_fields,
               wa_fields like line of t_fields.
    WHEN 'SORTUP'.(Ascending)
          loop at TABLE tc01-cols INTO wa_tc01  where  selected = 'X'.
          SPLIT wa_tc01-screen-name AT '-' INTO g_help g_fieldname.
          wa_fields-c_fieldname = g_fieldname.
          append wa_fields to t_fields.
          endloop.
          describe table t_fields lines l_index.
          c_count = 1.
          if c_count  <= l_index.
          read table t_fields into wa_fields index c_count.
          case c_count.
          when '1'.
          l_field1 = wa_fields-c_fieldname.
          when '2'.
         l_field2 = wa_fields-c_fieldname.
        and so on depending on the no of columns in the table control...
          endcase.
          endif.
          SORT t_tvbdpl_scr BY  l_fields1 l_fields 2......l_fieldn.
    Let me know if the above method will work!Also for the above method to work will the type of fields(columns on whihc sort function will be applied) matter???
    Thanks again for your time.

  • Sort function in web report using servlet

    Dear all
    Please help me this out. I'm doing an online report using servlet. When the report is displayed as a table on the web, is there a way to have a sort function-when you click on the tabs, it will sort the data accordingly.
    If I didn't state my question clearly, please let me know.
    Thank you all for your kind help!
    Grace

    You could probably do that using Javascript, but it's beyond my competence to even suggest how. Alternatively you could make the tabs behave as buttons that send a "sort me" request to the server, which would send out new, resorted, HTML.

  • Using SORT function in mapping

    Hi,
    I am having trouble getting my head around using the SORT function.
    My interface is IDOC to File, The IDOC has a repeating segment (PAYLOAD) that can be of 3 types, either type A, B or C (this is set using a "TYPE" field).
    In my file structure I have a repeating "ROW" element which has all of the fields for each row.
    I want to group all the Type A data together, the Type B together and the Type C.
    I have tried the following mapping on the "ROW" element but it doesn't seem to work:
    "TYPE"--"sort"Split By Value (Value Change)--collapseContext--"ROW"
    for each of the mappings under ROW I just have fields copied directly.
    I think I am doing something wrong.
    Thanks.

    Hi,
       You could make this mapping
         TYPE --- +----------------+     +----------------+
               |                |     |                |
               | Concat         | --- | mySortFunction | --- NAME
               |                |     |                |
         NAME --- +----------------+     +----------------+
         TYPE --- +----------------+     +----------------+
               |                |     |                |
               | Concat         | --- | mySortFunction | --- ADDR
               |                |     |                |
         ADDR --- +----------------+     +----------------+
       Where source code of mySortFunction is like this:
    public void mySortFunction(String[] inputValues,ResultList result,Container container){
         for(int i=0;i<inputValues.length;i++)
              if(inputValues<i>.substring(0,1).equals("A"))
                   result.addValue(inputValues<i>.substring(1, inputValues<i>.length-1);               
         for(int i=0;i<inputValues.length;i++)
              if(inputValues<i>.substring(0,1).equals("B"))
                   result.addValue(inputValues<i>.substring(1, inputValues<i>.length-1);
         for(int i=0;i<inputValues.length;i++)
              if(inputValues<i>.substring(0,1).equals("C"))
                   result.addValue(inputValues<i>.substring(1, inputValues<i>.length-1);
       It is very simple. You concat TYPE whit your data, and then you sort all queue, so you have a new sort queue data. You must only then put out data.

  • Getting UNCAUGHT_EXCEPTION CX_WD_CONTEXT at using alv sort function

    Dear colleagues,
    I developed a simple application which displays records in an ALV and at lead-selection shows detailed data in a form. Everthing is working fine except one is clicking on the sort functionality at the top of the ALV short dump is thrown.
    In trx ST22 I find :
    The lead selection has not been set. V_DEFAULT
    "UNCAUGHT_EXCEPTION" "CX_WD_CONTEXT"
    "CL_WDR_CONTEXT_NODE===========CP" or "CL_WDR_CONTEXT_NODE===========CM00R"
    "_RAISE_ELEMENT_NOT_FOUND"
    Lead selection is checked and also debugging the code did not bring me any further.
    Any help is greatly appreciated.
    Thanks in advance
    Michael

    Hi Regina,
    first of all thanks for your quick answer and explanation. I'm not sure what you mean with 'register to the standard functions of the ALV' because this is a functionality which works in other ALVs without register any event method to them or do you mean that in my case I have to react to the sorting in a new method in the view controller? Concerning 'refill the subnode via supply function' I'm doing this already.
    Disabling the sorting is no option anymore because the users already know and love this feature
    Regards
    Michael

  • I wanna use a HashMap instead of an array..but how ??

    Here's the class I'm using...
    public class Group {
         private Student[] list;
         public final int GROUPE_SIZE;
         private float[] finalGrades;
         public Group(int size) {
              GROUPE_SIZE = size;
              list = new Student[size];
         public void addStudents(Student[] list) {
                   this.list = list;
         public Student[] getList(){
              return list;
         public void setFinalGrades() {
              finalGrades = new float[GROUPE_SIZE];
              for (int i = 0; i < GROUPE_SIZE; i++) {
              finalGrades[i] = list.getFinalGrade();
              Arrays.sort(finalGrades);
         public float getLowestGrade() {
              return finalGrades[0];
         public float getHighestGrade() {
              return finalGrades[GROUPE_SIZE-1];
         public float getAverage() {
              float total=0.0f;
              for (int i=0; i < GROUPE_SIZE; i++) {
                   total+= finalGrades[i];
              return total/GROUPE_SIZE;

    I have to replace all the arrays in this class by using the HashMap, but I don't know how
    In order to know how, you need to know why.
    It looks like your class provides grades for students. Now, a Map (of which HashMap is an implementation) provides for mapping from one object to another. In your case, you probably want to look up students' grades, so your mapping would be "student-->grade"
    Read the collections examples linked above and you should be well on your way - but just remember that you need to know the "why" before the "how," otherwise you'll end up in a mess. Understand what it is you're trying to do, what the need is that your code satisfies.

  • Sort function issue...

         public void sortDate() {
              ArrayList<Round> temp = new ArrayList<Round>();
              ArrayList<Round> list = new ArrayList<Round>();
    //rounds is and arrayList defined in the class
              rounds.trimToSize();
              temp = rounds;
              int oldestIndex = 0, oldestRound = rounds.get(0).getDate();
              // Sort date from oldest to newest based on yymmdd format
              for (int i = 0; i < temp.size(); i++) {
                   oldestIndex = temp.get(0).getDate();
                   for (int j = 0; j < temp.size(); j++) {
                        if (temp.get(j).getDate() < oldestRound) {
                             oldestRound = temp.get(j).getDate();
                             oldestIndex = j;
                   // Add oldest in the pass to list
                   list.add(temp.get(oldestIndex));
                   temp.remove(oldestIndex);
              // After all passes to sort dates list is set to this.round
              this.rounds = list;
         }What is wrong with this sort function?

    wiebs2334 wrote:
              for (int i = 0; i < temp.size(); i++) {
                   temp.remove(oldestIndex);
              }You are iterating over the temp arraylist from 0-temp.size(), during that time you are removing elements. This is most likely the cause of your index out of bounds exception.
    A solution is to use an iterator and the corresponding remove methods.
    Mel

  • Sort functionality in Data Grid

    Hi Gurus,
    I am new to this DataGrid control.I want to establish the sort functionality when clicking on the headercolumns as in matrices.
    (ie.When double clicking the header column , sort the data in ascending or descending order of that column) like in system form matrices.
    How ever this is not possible when I tried with grid control.
    The problem I am facing is that I cannot get the column headers of the grid programmatically.(in duble click event or itempressed event)
    Anybody did this one previously? Also how
    we can change the column order of the grid using screen painter?
    The columns that actually come visible in the grid  are actually columns of the linked datatable object.
    In the designer ,there is no "swap" button for column re-ordering.
    Only one way I know is changing the query associated with datatable.
    This is a crucial thing ,since client may ask for re-ordering of columns frequently.
    Can anybody help?
    Regards,
    Deepesh

    Hi Deepesh,
    1. This functionality is not available with the SDK. Thus it's not possible to change it on the fly. Your only option is to change the query associated with datatable (as you mentioned). You may set up a user preference table, that the user can configure with its preference. That's the best you can do.
    2. To swap the columns in screen painter you must use SBO 2005 (it's not available on previous release). What you must do is, click on the one column you want to swap and the other you want to swap and click on the swap button (on the left bottom of the page in the columns tab)

  • How do I create a Dynamic java.sql.Date ArrayList or Collection?

    I Have a MySQL table with a Datetime field with many values inserted.
    I want to know which is the Best way to capture all the Inserted DB values inside a Dynamic Array.
    I get errors that state that I should use Matching data-types, and plus I don't know how to create or fill a Dynamic Date ArrayList/Collection.
    Please Help, I need this urgently...

    package pruebadedates;
    import java.sql.*;
    * @author J?s?
    public class ClaseDeDates {
        /** Creates a new instance of ClaseDeDates */
         * @param args the command line arguments
        public static void main(String[] args) {
            java.sql.Date aDate[] = null;       
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con = DriverManager.getConnection("jdbc:mysql://localhost/pruebafechas", "root", "picardias");
                    if(!con.isClosed()){
                    stmt = con.createStatement();
                    stmt.executeQuery ("SELECT dates FROM datestable");
                    rs = stmt.getResultSet();
                        while (rs.next())
                        aDate[] = rs.getDate("dates");
            catch(Exception e)
               System.out.println(e);
            //System.out.println(aDate);     
    }Hi, There is my code and the errors that I get are:
    found : java.sql.Date
    required: java.sql.Date[]
    aDate = rs.getDate("dates");
    Actually I have No idea as How to get a Result set into an ArrayList or Collection. Please tell me how to do this Dynamically. I have like 25 records in that Database table, but they will grow, so I would really appreciate to know the code to do this. I suspect my problem is in the bolded part of my code.
    Thank you very much Sir.

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

  • How to access Call Back Functions using *.dll in the Labview?

    Hai,
    I am Pavan Ram Kumar Somu.
    I am new to Labview, currently I am working on MVB Interface.
    I need to access the API functions from *.dll file in Labview, as of now , I am doing this with Call function Library node in Labview but it does not support the following data types like
        1. Pointer Arguments(To which memory it points in Labview)
        2. function pointers Arguments
        3 .pointers in structures and pointer structures in structures and many other data types.
    Please Answer the below queries also:
    1. How to pass pointer arguments to API functions in DLL and how to collect pointer  
        return types from API functions in DLL
    2. How to pass structure arguments to API functions in DLL and how to collect structure
        return types from API functions in DLL
    3. How to use callback functions(nothing but function pointers) in Labview and how to
        collect callback fuctions return types from API functions in DLL
    I need your help while passing these datatypes to API functions in DLL from labview.
    Suggest me if there is any other alternative for implementing this task.
    I am referencing some examples here:
    Examples:
    I)
    Unsigned short int gf_open_device(void *p_device_config, unsigned long int client_life_sign_timeout, unsigned short int *device_error)
    void *p_device_config: How to access/pass these arguments in LabView and to which memory location it points in LabView.
    II) #include <windows.h>
         #include <process.h>
         HANDLE rcvEvent0, rcvEvent1;
    /* Function call*/
    CanGetReceiveEvent(handle[0], &rcvEvent0);
    Above is a piece of C code, Now I want to use HANDLE datatype which is windows based, how to use these type in the LABVIEW.
    With regards
    Pavan Ramu Samu

    "Somu" <[email protected]> wrote in message news:[email protected]...
    Hai,
    I am Pavan Ram Kumar Somu.
    &nbsp;
    I am new to Labview, currently I am working on MVB Interface.
    &nbsp;
    I need to access the API functions from *.dll file in Labview, as of now , I am doing this with Call function Library node in Labview but it does not support the following data types like
    &nbsp;&nbsp;&nbsp; 1. Pointer Arguments(To which memory it points in Labview)
    &nbsp;&nbsp;&nbsp; 2. function pointers Arguments
    &nbsp;&nbsp;&nbsp; 3 .pointers in structures and pointer structures in structures and many other data types.
    &nbsp;
    Please Answer the below queries also:
    &nbsp;
    1. How to pass pointer arguments to API functions in DLL and how to collect pointer&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp; return types from API functions in DLL
    &nbsp;
    2. How to pass structure arguments to API functions in DLL and how to collect structure
    &nbsp;&nbsp;&nbsp; return types from API functions in DLL
    &nbsp;
    3. How to use callback functions(nothing but function pointers) in Labview and how to
    &nbsp;&nbsp;&nbsp; collect callback fuctions return types from API functions in DLL
    &nbsp;
    I need your help while passing these datatypes to API functions in DLL from labview.
    &nbsp;
    Suggest me if there is any other alternative for implementing this task.
    &nbsp;
    &nbsp;
    I am referencing some examples here:
    Examples:
    I)
    Unsigned short int gf_open_device(void *p_device_config, unsigned long int client_life_sign_timeout, unsigned short int *device_error)
    &nbsp;
    void *p_device_config: How to access/pass these arguments in LabView and to which memory location it points in LabView.
    &nbsp;
    II) #include &lt;windows.h&gt;
    &nbsp;&nbsp;&nbsp;&nbsp; #include &lt;process.h&gt;
    &nbsp;&nbsp;&nbsp;
    &nbsp;&nbsp;&nbsp;&nbsp; HANDLE rcvEvent0, rcvEvent1;
    &nbsp;
    /* Function call*/
    CanGetReceiveEvent(handle[0], &amp;rcvEvent0);
    &nbsp;
    Above is a piece of C code, Now I want to use HANDLE datatype which is windows based, how to use these type in the LABVIEW.
    &nbsp;
    With regardsPavan Ramu Samu
    Search the forum (forums.ni.com) for callback, pointer or handle, and you'll find that it is all possible, but not very easy.
    e.g.: http://forums.ni.com/ni/board/message?board.id=170&message.id=88974&requireLogin=False
    Regards,
    Wiebe.

  • Sorting technique used by oracle for "order by" clause.

    Hi All,
    it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
    Issue i am facing :
    Table : xx
    Line Date
    1 05-06-2013 00:00:00
    2 05-06-2013 00:00:00
    when we query above table using order by date, it is returning line 2 prior to line 1. we would like to know why it is returning line 2 first?
    Regards,
    Ram

    >
    it could be very help to me if you provide some information about sorting technique used by oracle engine for order by clause.
    >
    Well ok - but be warned that many people wind up being sorry they ask that question. Hopefully Hemant's answer is what you really wanted.
    See 'Linguistic Sorting and String Searching' in the Oracle® Database Globalization Support Guide
    http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch5lingsort.htm
    Sorting will be controlled by the settings of NLS_LANGUAGE, NLS_SORT and NLS_COMP.
    Here is the doc page for NLS_SORT
    http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008393
    >
    NLS_SORT specifies the type of sort for character data. It overrides the default value that is derived from NLS_LANGUAGE.
    NLS_SORT contains either of the following values:
    NLS_SORT = BINARY | sort_name
    BINARY specifies a binary sort. sort_name specifies a linguistic sort sequence.
    >
    And the one for NLS_COMP
    http://docs.oracle.com/cd/B28359_01/server.111/b28298/ch3globenv.htm#i1008458
    >
    The value of NLS_COMP affects the comparison behavior of SQL operations.
    You can use NLS_COMP to avoid the cumbersome process of using the NLSSORT function in SQL statements when you want to perform a linguistic comparison instead of a binary comparison. When NLS_COMP is set to LINGUISTIC, SQL operations perform a linguistic comparison based on the value of NLS_SORT. A setting of ANSI is for backward compatibility; in general, you should set NLS_COMP to LINGUISTIC when you want to perform a linguistic comparison.

  • How does the SORT function in ALV grid work?

    Hi,
    I have a report for which the o/p is displayed in ALV grid format.There is one column in the O/p strcuture which is "No of days".Based on certain conditions,i need to display the value for some of the days as Negative e.g. " - 45".Becasuse of this,I have declared the field for the "No of days" of the type "CHAR".
    Now when i sort(using ALV grid SORT function) the list on basis of this column,it doesnt give me the correct o/p.
    CAN anyone tell me how do i handle this?I want the list to be sorted correctly on basis of the "No of days" column.
    Thanks!

    This is your Fourth Cross Posting in last three days on same issue!!
    CHAR type column doesnt work for SORT function in ALV grid!
    How to sort a column of type CHAR
    I dont,ve link for your Fourth Thread on same,though i'm short memory loss.

  • Sort Function is being Overridden by Some default

    I've created a simple HFR report using Financial Reporting Studio to do budget vs. actual on a particular dimension (cost center). The dimemsion member selected is part of an alternate heirarchy which aggregrates the same way that I'd like the report to display. The particular member is selected as Decendents Inclusive (and is defined in the report as opposed to a prompt) so that I can capture the two levels below the selected member.
    No matter what I do using the Sort function (Name, Heirarchy, Description) in the member selection area when it generates the report the hierarchy is upside down (base, level 1, level 2), completely contrary the the actual heirarchy in EPMA. What am I missing and how do I get it to display from the top down?
    Thanks!
    Edited by: user13058666 on Jun 2, 2010 10:47 AM
    Edited by: user13058666 on Jun 2, 2010 10:53 AM

    A file under Private What? Where are you seeing this and how are you accessing it?

  • Sorting XML using DOM4J

    Hi All,
    Below is a sample XML which needs to be sorted based on the "id" attribute of the "key" element.
    <?xml version='1.0'?>
    <main>
    <key id='16066'>
    <key id='16061'>
    <key id='11'>
    <key id='1'>
    <key id='2'>
    <key id='1001'>
    </main>
    I am trying to sort the XML using the below function using DOM4J
    List xmlList = document.selectNodes("//main/key","@id")
    But the List is not sorted based on the number.
    I found that this does not happen even through XSLT because
    When sorting in default mode, the sorting is performed using alphabetic string comparisons. If numbers are to be sorted according to their numeric value, data-type must be set to "number".
    for example : "<xsl:sort data-type="number"/>"
    But, how do we do this using DOM4J.
    Please advice how to sort the numbers in an XML without using XSLT
    Thanks in advance,
    Raju

    Write your own code that manipulates the DOM.

Maybe you are looking for

  • Hard Drive Failed - Is there a seperate warranty?

    My Hard drive just failed. It is a Toshiba, and I am wondering if the apple warranty is for everything in the Hard drive, or if there are seperate manufactor warranties that apply to their components? I really don't want to have to buy a new hard dri

  • SAP Memory Analyzer

    Hi experts. I've here the Enterprise Portal installed in HP-UX and I'd like to use the SAP Memory Analyzer see some problems. I can use it? How I configure it in my desktop? Thanks for your help.

  • Safari won't display maps

    My Safari won't diplay maps from either Google Maps or MapQuest. I'm running OS10.3.9 and Safari 1.3.2 (V312.6). I have the cookies on for sites I go to. Maps display when using Firefox.

  • Aperture 3.5 projects: Some are missing from Library listing

    I use Aperture 3.5.1 with OS 10.9.2, and I have studied the various pages of Aperture manuals, and read quite a few Questions, and I think I understand the difference between projects and albums and between managed and referenced files. But I am puzz

  • Need help w/ G4 Power Mac PLEASE!

    I bought a used & ancient I know Mac for my kids to use for school project ect. It is a G4 Power Mac. It came w/ all the originial cd's. The guy told me they had been using it mainly his kids as well but he took everything off it & cleaned it to orig