Collections.sort() - sort on multiple fields?

I have a collection of objects in a List that I need to be able to sort on each field individually. For example, the data in the List is eventually displayed on a table in a web page. The user is able to click on a column header and the table is to be refreshed with the list contents sorted by that column (asc/desc).
I would rather not re-query the DB for this list (it's pretty static and already saved in memory). So if I use the Collections.sort(myList, new Comparator() { ...} ) method, is it possible for me to pass the field/direction of the sort into the Comparator? Or, do I have to define individual Comparators for every field that the user can sort by and surround it all by an ugly switch statement?

Honestly I think that a re-query to the DB is the best approach. Remember that any decent DB engine will cache queries so it will really only have to re-perform the sort algorithm.
Commercial databases are very fast and almost never the source of a performance bottleneck.
I realize this isn't the answer you want, but in my experience it is the best solution, if you really can't stand to re-query then as mentioned creating your own comparator is the way to go.

Similar Messages

  • How to Sort JTable data using Multiple fields (Date, time and string)

    I have to fill the JTable data with some date, time and string values. for example my table data looks like this:
    "1998/12/14","15:14:38","Unicorn1","row1"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/17","12:14:12","Unicorn4","row6"
    Now the Sorted Table should be in the following way:
    "1998/12/17","12:14:12","Unicorn4","row6"
    "1998/12/14","15:14:40","Unicorn4","row3"
    "1998/12/14","15:14:39","Unicorn2","row2"
    "1998/12/14","15:14:38","Unicorn1","row1"
    ie First Date field should be sorted, if 2 date fields are same then sort based on time. if date and time fields are same then need to be sorted on String field.
    So if any one worked on this please throw some light on how to proceed. I know how to sort based on single column.
    But now i need to sort on multiple columns.So what is code change in the Comparater class.
    Thanks in advance.. This is urgent....

    I think your Schedule objects should implement Comparable. Then you can sort your linked list using the Collections.sort() method without passing in a Comparator.class Schedule(Date date, String class) implements Comparable
      public void compareTo(Object obj)
        Schedule other = (Schedule)obj;
        return date.getTime() - other.getDate().getTime();
    }

  • Is it possible to sort by multiple fields?

    Is it possible to sort the music library by multiple fields in a prioritised order? For example, I would like to sort by the following columns, in the following order:
    Album Artist
    Album
    Track Number
    for some reason I can't seem to do this, sorting by Album artist alone is not working for me, as some CD's I've imported have featured artists and this breaksup the listing order.
    Thanks

    Thanks Thomas
    Unfortunately, this solution did not work for me, cover flow still shows multiple instances of the same artwork for various groups of tracks from the same album.
    The thing I don't understand is why sorting by the "sort album artist" field does not group all the tracks from an album together.
    My specific example (I still can't get a screenshot posted):
    I have two Gwen Stefani albums, both ripped from CD (not imported from the itunes store). both albums have a majority of track where Gwen is the only artist and two or three track with featured artists. I have filled the "album artist" and "sort album artist" tags to all read Gwen Stefani, however, if I sort by either of these columns (in cover flow mode), what I get is this:
    all the tracks from one ablum where Gwen Stefani is the artist
    then all the tracks from the other album where Gwen Stefani is the artist
    then (in alphabetical order by featured artist) the remaining tracks from both albums - ie, the albums are mixed up
    for each group of track I see an cover flow art work.
    I should say that I have turned off the compilation tag on all of my albums because this ends up saving the file in a compilation folder, not in the artist folder on my hard drive - but it doesn't make a difference either way to the way I see the files sorted in itunes.
    It's really frustrating!

  • In list view: Why don't searches include results from the Collections field? Why won't the Collections column sort properly?

    In list view: Why don't searches include results from the Collections field? Why won't the Collections column sort properly?

    I create a new index on column2, (INDEX_N3)
    and change SQL to
    select 1 from table T1 where
    T1.COLUMN_002 = '848K 36892'
    This time INDEX_N3 will be used.
    but change SQL to
    select 1 from table T1 where
    T1.COLUMN_002 = '848K 36892'
    and T1.COLUMN_004 = '1000'
    The explain plan will show full scan.
    Why?
    Thanks.

  • Is it possible to do sorting on multiple field inside a GROUP

    Hi
    I am wondering if it is possible to do a multiple sorting on multiple column/fields?
    When I right click on Change Group on the report
    on the "Change Group Options" window, it only has one field which allow you to sort in ascending/ descending order.
    I notice that it also has another checkbox which called Use a formula as Group Sort order, I am not quite sure how to use it to sort multifield/column.
    E.g.
    I have a table which has 5 fields
    I would like to sort it by TotalSpend, TotalEarned, Department, ...etc
    I would be grateful, if you can show me how to do a group sorting for multi column/fields
    Thanks in advance.

    To Sastry,
    Thanks for your information, unfortunately, I am using Crystal report XI.
    To Sandra,
    <<Yes, go into the Group expert and select them in the order in which you want them sorted>>
    Do you mean create different group to do the sorting?
    Could you show me how to create a formula which allow crystal report to do the sorting on multi-field.
    Thanks in advance.

  • Sorting on a Formula field

    Everytime I try to do a sort on the formula field below, I can't sort on the field.  It doesn't even show the field in the explorer window to sort on.  The formula is below.
    Sum ({fct_CurrentSales.Cases}, {@upc}) /
        (tonumber(Maximum ({vw_dim_Product.CA_MPN_JMelBoxesPerPallet}, {@upc}))) / {Command.Previous Fiscal Month}

    Sorting is done at record level and you're using a sum in your formula as well as a maximum value.  Not sure about what is being done in the {@upc} formula but it may be affecting it as well.
    Look at your user guide and look up the multiple passes CR makes and what is done in each pass.
    (I used to keep a copy of the multiple pass flowchart on the wall above my computer as it contains good information on what can be done and when during the report generation.)
    Sum ({fct_CurrentSales.Cases}, {@upc}) /
    (tonumber(Maximum ({vw_dim_Product.CA_MPN_JMelBoxesPerPallet}, {@upc}))) / {Command.Previous Fiscal Month}

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

  • I've been deleting the info in the "Sort..." fields, but when I plug my iPod into my computer iTunes repopulates the fields I deleted.  How do I stop it from doing that?

    I've been deleting information I don't want in the "Sort..." fields (like getting rid of "Deluxe Edition" markers, etc.), but when I plug my iPod into my computer iTunes repopulates the fields I deleted.  This only happens for a few artists, and it's the same artists every time this happens.  How do I stop it from doing that?  It makes it measurably harder for me to control the organization of my library.

    Hi donfrommars,
    Welcome to the Apple Support Communities!
    Please use the following article for information and instruction on deleting the U2 album from your devices and account.
    Remove iTunes gift album "Songs of Innocence" from your iTunes music library and purchases
    Have a great day,
    Joe

  • Defining sort order using parameter fields

    Post Author: vandersee
    CA Forum: General
    I've created a report, the contents of which is sorted depending on a parameter selected (method used is as described in the help topic entitled "Defining sort order using parameter fields".  Is it possible to vary the Sort Direction (ascending/descending) using parameters also, so that if I choose to sort by field A it will be ascending, but descending if I choose to sort by field B?

    Post Author: V361
    CA Forum: General
    You can create a Parameter {?Sort Order}  make it a string, and add items A to Z and Z to A and a formula and sort the group using the formula.
    Group Expert, select the group, select options, check use a formula as group sort order
    if {?Sort Order} = "A to Z" then crAscendingOrder else crDescendingOrder
    And your group will sort based on what is selected in the parameter.

  • Applying Sorting for the Month Field

    Hi,
    When i apply sort to the month-name field for each quarter(Q1,Q2..), it sorts as 1)February 2)January 3)March..
    Its sorts the month-name field in alphabetical order(F,J,M) not in the usual 1)January 2) February 3)March order..
    To sort this issue i added the numeric field called month with values 1,2,3..
    How to sort the month-name field as January, February???

    And if you're still struggling, [read this|http://blog.davidg.com.au/2011/03/sorting-months-in-webi.html].

  • SORT Not merging similar fields if there are any editable fields in the ALV

    Hi All,
    I have two issues with my OOPS ALV report.
    1) Standard sort is not working :
    Output of the report looks like this
    WBS    TEXT          Period 1  Period 2
    A           Total hours     1         1
    A           Total hours     1         1 
    A           Total COSt     1         1
    A          Total COST     1         1
    My agenda is to calculate sub total of period1 and period 2 based on fields WBS and TEXT, my output should look like
    WBS    TEXT          Period 1  Period 2
    A          Total hours         1           1
                                         1           1
    Total hours                     2           2 ( Sub total )
    A          Total COST        1         1
                                         1         1
    Total COST                    2         2 ( Sub total )
    To achieve this i pass these two fields in the sort table and pass field subtot = 'X' for TEXT field.
    It is working fine, i am getting the sub totals but the WBS field are not grouped( Even though it is a standard functionality).
    my output looks like
    WBS    TEXT          Period 1  Period 2
    A         Total hours   1         1
    A         Total hours   1         1
    Total hours               2         2 ( Sub total )
    A      Total COST      1         1
    A      Total COST      1         1
    Total COST              2         2 ( Sub total )
    I have few editable fields in my output, i came to know this issue is because of the editable fields. have anybody come across the same error.
    Please let me know how to achieve the standard sort ( Merging similar values ) functionality even if the output has editable fields.
    2) IS it possible to get two Grand total based on a field value . In my example , my TEXT field will always have value either  'Total hours' or 'Total COST'
    my output should look like this.
    WBS    TEXT          Period 1  Period 2
    A      Total hours     1         1
                                  1         1
    Total hours(A)          2         2 ( Sub total )
    A      Total COST     1         1
                                  1         1
    Total COST(A)         2         2 ( Sub total )
    B      Total hours      1         1
                                  1         1
    Total hours(B)          2         2 ( Sub total )
    B      Total COST      1         1
                                    1         1
    Total COST(B)           2         2 ( Sub total )
    GRAND TOTAL HOURS    4         4
    GRAND TOTAL COST       4         4.
    Response will be appreciated.
    Thanks & Regards,
    Rajanidhi Rajasekeran
    Edited by: Julius Bussche on Jul 14, 2008 7:39 PM

    Hi
    If I make  the editable field to non editable then sort & cell merge is happening but if I make any of the field as editable then merge is not working shall i request you the solution
    Regards-Sreeni

  • Sort recordset by 2 fields

    I am aware that if you would like to sort records by 2
    fields, you list both fields separated by a comma after ORDER BY
    (i.e. ORDER BY Name, Date)
    With the above code, the only way records will sort by Date
    is if they are identical other than by their date.
    Now what if I would really like to do is first sort records
    that share a common Name value regardless of other field values and
    then sort by Date ( Something like "First ORDER BY Name which
    contains the value of "PC" and then ORDER BY Date DESC")
    Can this be done?

    You can use a CASE statement in the ORDER BY clause.
    "aonefun" <[email protected]> wrote in
    message
    news:g7fvjq$qgs$[email protected]..
    >I am aware that if you would like to sort records by 2
    fields, you list
    >both
    > fields separated by a comma after ORDER BY (i.e. ORDER
    BY Name, Date)
    >
    > With the above code, the only way records will sort by
    Date is if they are
    > identical other than by their date.
    >
    > Now what if I would really like to do is first sort
    records that share a
    > common Name value regardless of other field values and
    then sort by Date (
    > Something like "First ORDER BY Name which contains the
    value of "PC" and
    > then
    > ORDER BY Date DESC")
    >
    > Can this be done?
    >

  • Passing multiple fields as addition to  "end at " statement

    Hi All
    I dont think I can pass multiple fields to END AT statement.
    I need to sum at end of few field values in table .what is the best method of acheving this.
    Thanks in Advance
    Regards
    Vinay Kolla

    have different control blocks, and make sure you sort on all of the fields which you are using the control statements.

  • New to the product - question about validating multiple fields as a group

    I have a static form that I'm building from a word document.  Part of that form requires a person to fill any 3 out 5 text fields.
    Since it looks like scripts are applied on a field by field basis, is it possible to have a script that encompasses multiple fields? 
    Would any script need to be applied to each field in turn?
    Assuming the answer to question 1 is a yes, how would you script it to require x number of fields out of a total of y to have some sort of content in order to validate?
    I'm pretty familiar with JavaScript and am looking at the Scripting reference guides but was hoping for a helping hand to get me there quicker as I'm in a bit of a time crunch - doing 18 forms with validation and database connectivity by January 15 certainly qualifies in my book.
    I would assume you'd do something like this but am unsure of the syntax...
    Get values of each field
    Set a valid counter variable for the number of fields with content
    If field 1 is not empty, increment the valid counter
    (rinse and repeat)
    if the valid counter is less than 3 throw an error message
    Many thanks in advance for any help offiered

    1). Yes, scripting within Livecycle can be for a single field or even static text, images and other artifacts within the PDF. Really anything, within Adobe's reason, when it comes to scripting.
    2). It depends on what you want to do. Things like field validations, calculations and other instances where fields are tied togther really dictate how the script runs.
    3). Fields that have calculations or validations with them work in the same, I believe. So for example I have a PDF that I made that is an Excel-type sheet that contains a few hundred cells and every single one has some type of validation or calculation associated with it. I generally run the calculations/validations from the user inputting the data and then after that the script runs, but again, it really dpeneds on what you are doing and with what, so answering some of your questions are a bit difficult.
    Javascrip/Formcalc are wonderful tools within PDF, but don't forget the Action Builder (Tools -Action Builder). It is a set of preloaded actions that are turn-key. Just select the cells that will have the action and select the result you want from the preloaded list of actions, using those actions can get you very far, and most of all; they are quick to implement without researching code. So for example, you could use the Action Builder to create an action that checks certain fields and if they are null to return a 1 value to a specific numericField (these could be hidden). Then have a "total" numericField (this would be your counter) that adds all of those fields with the 1 in it. Then create another Action Builder for that "total" numericField and if it is less than 3, display a message box that is a warning.

  • Customised metadata - search for multiple fields?

    Background: I'm logging a STACK of footage and attempting to arrange it all by a series of different keyword categories (the day the footage was shot, location, camera type, content type, key players, etc). Each category has multiple variables (ie: in the camera category the options are Sony FS700, Canon 5D, Canon 600D, GoPro). I'm adding custom fields via the PPr Project Metadata>Add Property function using a simple Boolean tickbox.
    Question: Is there a way to sort and search the custom fields? For example if I wanted to pull up all the footage shot on day 5, with the Sony, that comprises of interview content with a particular person is there a way to search for all these fields? I've been able to search for one keyword if I tag the material but so far searching and organising by multiple fields has eluded me.
    The long way round is to create multiple bins and/or sequences for each variable in each category by hand, but that's a little tedious and has the potential to bloat the project. Any ideas to solve the problem? I've come from FCP a few months ago so the metadata side of PPro is still something I'm getting my head around. Thanks for reading!
    EDIT: I'm running PPro CC for reference and can install and use Prelude if it helped.

    For the time being I'm using a workaround employing titles above the footage to signify the relevant categories, and tagging significant moments in clips with markers, but it is perplexing.. Premiere seems to employ metadata in a phenomenal way - such that I haven't come across in any other mainstream editor - I just wish it had the functionality to sort and manage all that metadata it is producing beyond the search bar in the Project window.
    Premiere gurus and Adobe affiniados: am I missing something obvious?

  • What is the best way to set property to multiple fields?

    Dear Experts
    My requirement is, I want to allow user to fill only some specific fields in the form. When user A opens the form, he may be able to fill Field1~Field10. And when user B opens the form, he may be able to fill Field11~Field20.
    I have implemented one solution as below to do this but the performance is poor.
    - Recursively poppulate all fields into array
    - Iterate all fields to make it read only (Field.access = 'readOnly')
    - Iterate all fields and compare with enabled fields list, if any field matchs then enable it (Field.access = 'open')
    (I have list of enabled fields for each user like this : form1[0].page1[0].ProjectNumber[0],form1[0].page1[0].CustomerName[0],form1[0].page1[0].Fi nishedGoodsNo[0],......)
    Is there a better way to reference multiple fields to set their property?
    I know, we can reference multiple fields using FormCal like Field[*] but is it possible to complete my case?
    Any suggestion?
    Thanks

    We make web application which accept the form designed by end user. So we try to make them most comfortable to use LyfeCycle Form Designer by creating tds template for them and it contains the script which enable/disable fields. So the user don't have to set all fields to read only. Our script will do it.
    Anyway I will adjust when enabling them.
    One more doubt.
    When I type in the script editor, it lists member :
    - all, the hint says "Returns the collection of like-named, in-scope nodes. If the node has no name, a like-classnamed collection is returned."
    - classAll, the hint says "Returns the collection of like-class, in-scope nodes."
    Can I get all fields by these member? get fields from class?
    It would be good if it can do.
    I try to check XFA reference and use them but cannot get how it work.
    Could you please suggest?
    Thanks

Maybe you are looking for