Sorting a collection

hello all,
i am tring to sort a two dim array of object , how can i print the dim array of object after sort?
package collection;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;
public class CollectionSort {
           public static void main(String args[])
                Object[][] data =
                         {"Color", "Red", "Red"},
                         {"Shape", "Square","Red"},
                         {"Fruit", "Banana", "Red"},
                         {"Plain", "Text", "Red"},
                         {"Plain", "Text", "Red"}
                List list = Arrays.asList(data);
                final Comparator stringCmp = new Comparator() {
                 String s1;
                    public int compare(Object o1, Object o2) {
                         s1 = o1.toString().toUpperCase();
                         String s2 = o2.toString().toUpperCase();
                         return s1.compareTo(s2);
                    public String toString(){
                         return s1;
                Collections.sort(list,  stringCmp);
                for (ListIterator<Object> it = list.listIterator();
                    it.hasNext();) {
                         String t = it.next().toString();
                         System.out.println(t);
}

You mustn't create something already created:
Collections.sort(list,  String.CASE_INSENSITIVE_ORDER);See: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER
Respect toString(), I have created a recursive toString for any object, included arrays or matrix:
public static String toString(Object object){
     String string;
     if(object.getClass().isArray()){
          StringBuilder arrayString=new StringBuilder("[");
          int length=Array.getLength(object);
          for(int i=0;i<length;i++)     {
               arrayString.append(toString(Array.get(object,i)));
               arrayString.append(", ");
          arrayString.setCharAt(arrayString.length()-2,']');
          string=arrayString.substring(0,arrayString.length()-1);
     else
          string=String.valueOf(object);
     return string;
}

Similar Messages

  • How to sort a collection based on their date?

    how do i sort a collection based on their respective dates which are in Calendar format?

    this is my codes
    /** This class is use to sort the call list base on their date
    import java.util.*;
    public class a implements Comparator
         /** compare the objects base on their types
         *     @obj1 the first object to be compared
         *     @obj2 the second object to compare with the first object
         public int compare(Object obj1, Object obj2)
         if (obj1 == obj2)
              return 0;
         if (obj1 == null || obj2 == null)
              return 0;
         if (!(obj1 instanceof Call) || !(obj2 instanceof Call))
              return 0;
         Call lhs = (Call) obj1;
         Call rhs = (Call) obj2;
         int s = lhs.getDate().compareTo(rhs.getDate());
         if (s != 0)     
              return s;
         return 1;
    this is the error
    a.java:21: cannot resolve symbol
    symbol : method compareTo (java.util.Calendar)
    location: class java.util.Calendar
         int s = lhs.getDate().compareTo(rhs.getDate());

  • How can I sort a collection of array with different object types in it ?

    Hi all,
    I have a collection of ArrayList; each array contains, at the first position, the same object type.
    I'd like sorting the collection by the name contained in the object at the first position of each array.
    Any suggestion ?
    Cheers.
    Stefano

    so you have a collection of a collection?
    My guess is that:
    You could subclass the arraylist and override it's compareTo method (I think that it implements comparable already but if not, go ahead and implement that interface).
    Or you could wrap your arraylist in another class that implements comparable.
    The key in my mind is correctly coding your compareTo method to look at the name in the first item of the arraylists. This should be doable and not too difficult.
    Correction: after reviewing the ArrayList api, I see that it doesn't implement the Comparable interface. You will have to make any class that either inherits arraylist or contains arraylist implement the comparable interface.
    One last thing: This question would probably have been better off in the java forum and not the Swing forum since it doesn't really involve Swing.
    Good luck!
    Edited by: petes1234 on Nov 19, 2007 6:17 AM

  • Manually Sort a Collection

    I would like to manually sort a Collection, and then save that sort when I save the Collection.
    In Bridge 1.0.4 (CS2), WinXP, manual sort seems to work only for a real folder.
    When I try to move a thumbnail in a Collection (result of a find operation), I get the international "NO" symbol (circle with a diagonal line). No manual sort seems to be allowed in Bridge CS2!
    Is it allowed in CS3?

    ejp is right.
    If you are talking about several unrelated sorts, you
    need a comparator per sort order.Just to get the full story: You could build a generic comparator and configure it according to the next sorting you want to do:
    Collection.sort(list, new GenericEmployeeCompare(SortOrders.SortByName));I very much doubt you'll want to, though. It will get overly complicated, and I don't see what you gain.
    If all sorting (all calls to Collections.sort()) happen from within one class, you can make your Comparator classes local to that class, so as to keep things together still.

  • How to sort a collection by two componets/Attributes

    Hello All,
    Scenario:
    I have a result table view with columns Contact Person Number, Central Block flag and Last name. At the instance of BP confirmation in IC this result table(result view displays the contact persons associated with the account id during the BP cofirmation) is filled in a sorted order based on the Contact Person Number.
    Requirement:
    Sort the result table by Central block flag followed by Contact Last Name.Hence how to sort the collection of the result table view based on two attributes Central Block and Last Name?
    Looking forward for your support.
    Regards,
    Harish P M

    Hello Harish,
    Good question. The framework doesn't seem to support this. When i needed this functionality, i had to create my own implementation of collection. You can inherit from CL_CRM_BOL_ENTITY_COL and overwrite several methods which do the sorting. Check the class CL_CRM_IPM_RAA_BOL_COL.
    Best Regards,
    Yevgen

  • Sorting a collection with least time complexity algorithm

    Hi ,
    I have a collection which is having data
    <AspectRow>
         key=2732ddb1-adf5-11dc-c76c-0013210f9b73
         createdBy=Administrator
         createdAt=2007-12-19 11:12:15.051
         lastChangedBy=Administrator
         lastChangedAt=2007-12-19 11:12:15.071
         title=cc
         description=cc
         type=Rating
         isActive=1
         isDefault=true
      </AspectRow>
    ,   <AspectRow>
         key=2c37f611-adf5-11dc-ce26-0013210f9b73
         createdBy=Administrator
         createdAt=2007-12-19 11:12:23.473
         lastChangedBy=Administrator
         lastChangedAt=2007-12-19 11:12:23.503
         title=bb
         description=dd
         type=Rating
         isActive=1
         isDefault=true
      </AspectRow>
    <AspectRow>
         key=2c37f611-adf5-11dc-ce26-0013210f9b73
         createdBy=Administrator
         createdAt=2007-12-19 11:12:23.473
         lastChangedBy=Administrator
         lastChangedAt=2007-12-19 11:12:23.503
         title=bb
         description=a
         type=Rating
         isActive=1
         isDefault=true
      </AspectRow>
    <AspectRow>
         key=2c37f611-adf5-11dc-ce26-0013210f9b73
         createdBy=Administrator
         createdAt=2007-12-19 11:12:23.473
         lastChangedBy=Administrator
         lastChangedAt=2007-12-19 11:12:23.503
         title=bb
         description=b
         type=Rating
         isActive=1
         isDefault=true
      </AspectRow>
    i would like to know how can i sort the collection based on the alphabetical order of atrribute title.
    Thanks and Regards
    Neeta

    Hi Jens,
    I tried writing my code as below
    Public class A
    Collection criteries =new ArrayList();
    for( int indexContext = 0; indexContext < criteriaContextAspect.size(); indexContext++) {
    IAspectRow contextRow = criteriaContextAspect.getAspectRow(indexContext);
    IAspect criteriaAspect = contextRow.getRelatedAspect(Constants.CRITERIES_RELATION_NAME);
    criteries.add(criteriaAspect.getAspectRow(0));          
    Collections.sort(criteries,new TitleComparator());
    Class TitleComparator implements Comparator
    public int compare(Object o1,Object o2)
    IAspectRow row1 =(IAspectRow)o1;
    IAspectRow row2 =(IAspectRow)o2;
    String t1= row1.getAttributeValue("title")
    Here when i compile i am getting an error Cannot resolve symbol criteries in
    Collections.sort(criteries,new TitleComparator());
    Kindly suggest what can be the reason for this....
    regards
    neeta

  • Problems sorting LR collections

    This is a slightly long story but necessary to explain the help I need and why! I have some 18000 photos which have been collected over several years and which in some cases have come from different cameras (metadata capture dates and file numbers in different formats) and from slides which have been digitized but now think they were taken (captured) on the date they were digitized. After a lot of effort I have grouped the photos into chronological LR  collections and have rated them so that I now have about 1500 photos "of interest" contained in these collections. The leading characters of the collection names are  in the format "year/month" (eg 1998/03) followed by a short text description. These now reside in about 50 different LR collections. The number of photos in each collection varies between 1 and 43.
    What I want to do is condense these 50 collections into a single master collection but keep them in the same chronological order Once I have done this I can use LR to apply an "indexing" number to all 1500 photos. I can then export the photos to a catalog and use the index for future sorting as I further refine the photos before printing. I will not need to worry about differing file names and inaccurate capture dates.
    I found a tutorial showing how to condense groups of catalogs into a master catalog but there seems no similar option to group collections which I find hard to believe. I have the latest LR5.7.1 version.

    To build on Modesto's comments: While collections allow you to provide a custom (manual) sort order, collection sets do not.  You can see that by clicking on the Sort: dropdown in the toolbar at the bottom of Library grid mode when you have a collection set selected in the Collections panel:
    So when you select a collect set, it will be ordered by Capture Time or some other criteria, but not by manual orders you imposed on each of its collections.
    Rather than making a collection set, you could make another collection called "Master" and then add all of the pics in each of your other collections to Master in turn.  Master will retain the order of the pics in which you added them.  To make that go fast, right-click Master in the Collections panel and do Set As Target Collection.  Then in chronological order, select each source collection in the collections panel.  Do Edit > Select All to select all the pics in the collection, then right-click the pics and do Add To Target Collection ("B" is the keyboard shortcut).
    Of course, if you update one of the individual collections, you'll have to manually update Master, which probably isn't what you want.
    Stepping back, you're trying to use collections for something for which they're not designed.  You want to set and maintain the chronological ordering of pics, and digital-asset-management tools like Lightroom provide a number of tools to let you use the "capture date" metadata field to do precisely that.  You set the capture date of each pic, and then the tools will let you sort, slice, and dice by date very easily.
    Digital cameras make this nearly painless, since they automatically set the capture date of pics.  But the rub you've encountered is that you've got a large number of scans, and scanner software doesn't set the capture date for you (how could it? -- it doesn't know what the date should be).   So you need to set the capture date of your pics.   Unfortunately, LR was explicitly designed primarily for manipulating pics from digital cameras, and while many of us use LR to also manage scans, LR itself doesn't make it that easy, starting with its clunky Edit Capture Date command.
    When I scan a group of slides, they're typically grouped by time (e.g. in numeric order, or from the same year, or whatever).  I import the scans into LR, and then use a temporary collection to put them in proper chronological order, using the date and slide number printed on the slide.   Typically, I know the year and month but not the day or time of a group, so I'd like to set all the pics in the group to have capture dates, say, of 1961/2/1 12:00:01, 1961/2/1 12:00:02, 1961/2/1 12:00:03, etc.  The clunky LR Edit Capture Command would make that exceedingly painful, but luckily, there are a couple of plugins, such as ExifMeta and Capture Time To Exif, that make it very easy.
    While this is a little more work than dragging each photo manually into a collection, as you've been doing, it's really not that much more work, and you're left with your pics assigned capture dates that any software tool can use to display and organize.  
    You've already got your collections organized by year and month, so using ExifMeta to assign capture dates to your scans shouldn't be that hard.

  • Images sorted in collections are gone

    It happened to us already several times that images we sorted into different collections suddenly do not longer belong to the collection. E.g. a collection containing about 125 images on one day does only contain 20 images on the next day. All others are gone (not deleted, but they do not longer belong to the collection) and there is no way to get them back to the collection but to sort them manually again.
    Why does this happen and how can we avoid it? It happened to different collegues already (on different computers - all using Adobe CS5.5)
    I hope to get an answer to that soon. We love the collection function but if it does not work correctly, there is no use for us...
    Thanks and greetings from Berlin!
    Claudia

    There was an old thread about this issue here:
    http://forums.adobe.com/message/3374043
    comment #19 clearly explains that CS5 Bridge when making the .filelist file for the Collection does not automatically change any apostrophes to %27 like CS4 Bridge would (similarly blank spaces get converted to %20 in CS5 just like CS4). 
    This bug was reported over a year ago and seems to be a simple fix - put back in the feature from CS4 that changed any single quote in paths of the images to %27 - How about it Adobe? I am working off of a server and can not change old folder filenames that contain the offending apostrophe.

  • Table sorter using collections

    hi
    does anyone has example for Column Sorting in jtable
    using Collections.
    thanks

    Have you looked here yet?
    http://www2.gol.com/users/tame/swing/examples/JTableExamples5.html

  • Unable to drag to re-sort in collections

    Suddenly after updating I am no longer drag to re-sort an image within a collection.
    I get this error:
    Datavase "[The location of my catalog.lrcat":
    AgLibraryCollectionimageOzsortorder.positionincollection may not be NULL
    Statement: INSERT OR REPLACE INTO AgLibraryCollectionImageOzSortOrder
    (Collectionimage, collection, positionincollection, ozSortOrder )
    VALUES( ?, ?, ?, ? )
    Any ideas?

    Some others have reported this on the official feedback forum:
    LIGHTROOM 5.5: Error when moving grouped images in Grid view.
    Lightroom CC Re-Sorting within a collection giving error message
    LightRoom 5.5 OSX 10.9.3: Custom sort within a collection gives an error (screenshot attached)
    Please add your opinion and votes to those threads.  The threads include some workarounds you might try.

  • LR4 Flag Sorting in Collections no longer working

    I get that the flags are carring over to collections now, when before they didn't.  In lightroom 4 beta, I didn't have problems tagging some of the flagged images as regects and then filtering the results from those left flagged, to those changed to rejects.  Now that I have upgraded, none of my flag filtering is working.  If I select flagged, i get nothing.  If i select rejects, I get nothing.  How can I fix this?  As a wedding photographer with thousands of images in a collection, this will be quite frustrating to go back through all these images to manually move the rejects out of the way.

    http://forums.adobe.com/message/4250910#4250910

  • Sorting a Collection with dynamic columns using a custom compare function for multiple columns

    I need help and ideas on how to sort a ListCollectionView.  My problem is complicated by 3 requirements-
         1. The column values contain HTML tags that needs to be removed before sorting (use custom compareFunction to strip HTML)
         2. The columns are dynamic, so dataField names are not known at compile time (need a single compareFunction for all columns)
         3. The data is used in an AdvancedDataGrid so multi-column sorting is required
    I have figured out how to solve any 2 of the 3 requirements.  However, I am having difficulties supporting all 3 requirements.
    Any help or ideas would be greatly appreciated.  Thanks.

    After playing with this some more I think I've figured out a solution.  This seems to work in initial testing.  Also, there is not a need to capture the current sort column in the headerRelease event which many offered solutions suggested.  Another benefit to this solution is that keyboard initiated sorting is handled also.  Whereas the headerRelease event is only triggered by a mouse click on the column header and special handling is required if the user uses the keyboard to access the column header.
    One point that I don't understand is how ascending/decending order is determined.  Behavior seems to be different between a single SortField versus multiple SortFields.  Notice how the compareResults are handled for the different situations.  Anyone out there know why???
     private function colSortCompareFunction(obj1:Object, obj2:Object, fields:Array = null):int{
         var compareResults:int = 0; 
         var newObj1:Object = new Object(); 
         var newObj2:Object = new Object();
          // should not be a condition that is met   
         if (_dataProviderDetails.sort.fields == null)     {
              var s:Sort = new Sort(); 
              var f:Function = s.compareFunction; 
              return f.call(null, obj1, obj2, fields);     }
         // when a single column is selected for sorting   
         else if (_dataProviderDetails.sort.fields.length == 1)     {
              var firstFld:SortField = _dataProviderDetails.sort.fields[0];
              newObj1[firstFld.name] = stripHTML(obj1[firstFld.name]as String);          newObj2[firstFld.name] = stripHTML(obj2[firstFld.name]
    as String);
              compareResults = ObjectUtil.compare(newObj1[firstFld.name], newObj2[firstFld.name]);
               return compareResults;     }
         // when multiple columns are selected for sorting   
         else       {
              for each (var fld:SortField in _dataProviderDetails.sort.fields)          {
                   newObj1[fld.name] = stripHTML(obj1[fld.name]
    as String);               newObj2[fld.name] = stripHTML(obj2[fld.name]
    as String);
                   compareResults = ObjectUtil.compare(newObj1[fld.name], newObj2[fld.name]);
                    if (compareResults != 0)               {
                        if (fld.descending)                    {
                             return compareResults * -1;                    }
                        else                      {
                             return compareResults;                    }
               return compareResults;     }
    Does anyone see any problems with this solution?
    NOTE:  stripHTML(String) is a simple function using regular expression to remove HTML tags.
    Thx

  • Advanced Data Grid Sorting / Grouping Collection

    Ok, basically here's the issue..
    I have an advanced data grid with a tree view. It goes two
    levels deep
    so:
    Report Type
    |-------------------- Company
    |--------------------------------------- Report 1
    |--------------------------------------- Report 2
    |--------------------------------------- Report 3
    |-------------------- Company 2
    |--------------------------------------- Report 1
    |--------------------------------------- Report 2
    |--------------------------------------- Report 3
    Report Type 2
    |-------------------- Company
    |--------------------------------------- Report 1
    |--------------------------------------- Report 2
    |--------------------------------------- Report 3
    |-------------------- Company 2
    |--------------------------------------- Report 1
    |--------------------------------------- Report 2
    |--------------------------------------- Report 3
    etc..
    Report and Company are Nodes (folders) and are being sorted
    alphabetically by default.
    The individual reports (Report 1,2,3, etc..) are not being
    sorted in any way that I can figure out. I need to sort them by
    date, but no matter what I've tried I can't get it to work.
    I tried a SortCompareFunction on the advancedDataGridColumn
    that displays each report, and it works *IF* I click the header...
    but if I dispatch the header_release event via AS3, nothing
    happens.
    I even set up a test:
    dg.addEventListener(AdvancedDataGridEvent.HEADER_RELEASE,heard);
    dg.dispatchEvent(
    new AdvancedDataGridEvent
    AdvancedDataGridEvent.HEADER_RELEASE,
    false,
    true,
    0, // The zero-based index of the column to sort in the
    DataGrid object's columns array.
    null,
    0,
    null,
    null,
    0
    function heard(e:Event) {
    trace("I HEAR IT!");
    trace(e.type);
    I set that up on a button so I can dispatch the event with a
    click. Every time I click the button, the header release event
    listener goes off, but the actual advanceddatagrid remains
    unchanged until I actually click on it's header..
    Any help would be *GREATLY* appreciated... I've been stuck on
    this problem for two days now :(

    "AnakinJay" <[email protected]> wrote in
    message
    news:[email protected]...
    > Ok, basically here's the issue..
    >
    > I have an advanced data grid with a tree view. It goes
    two levels deep
    > so:
    > Report Type
    > |-------------------- Company
    > |--------------------------------------- Report 1
    > |--------------------------------------- Report 2
    > |--------------------------------------- Report 3
    > |-------------------- Company 2
    > |--------------------------------------- Report 1
    > |--------------------------------------- Report 2
    > |--------------------------------------- Report 3
    >
    > Report Type 2
    > |-------------------- Company
    > |--------------------------------------- Report 1
    > |--------------------------------------- Report 2
    > |--------------------------------------- Report 3
    > |-------------------- Company 2
    > |--------------------------------------- Report 1
    > |--------------------------------------- Report 2
    > |--------------------------------------- Report 3
    > etc..
    >
    > Report and Company are Nodes (folders) and are being
    sorted alphabetically
    > by
    > default.
    > The individual reports (Report 1,2,3, etc..) are not
    being sorted in any
    > way
    > that I can figure out. I need to sort them by date, but
    no matter what
    > I've
    > tried I can't get it to work.
    >
    > I tried a SortCompareFunction on the
    advancedDataGridColumn that displays
    > each
    > report, and it works *IF* I click the header... but if I
    dispatch the
    > header_release event via AS3, nothing happens.
    >
    > I even set up a test:
    >
    dg.addEventListener(AdvancedDataGridEvent.HEADER_RELEASE,heard);
    >
    > dg.dispatchEvent(
    >
    > new AdvancedDataGridEvent
    > (
    > AdvancedDataGridEvent.HEADER_RELEASE,
    > false,
    > true,
    > 0, // The zero-based index of the column to sort in the
    DataGrid object's
    > columns array.
    > null,
    > 0,
    > null,
    > null,
    > 0
    > )
    >
    > );
    >
    > function heard(e:Event) {
    >
    > trace("I HEAR IT!");
    > trace(e.type);
    >
    > }
    >
    >
    > I set that up on a button so I can dispatch the event
    with a click. Every
    > time I click the button, the header release event
    listener goes off, but
    > the
    > actual advanceddatagrid remains unchanged until I
    actually click on it's
    > header..
    >
    > Any help would be *GREATLY* appreciated... I've been
    stuck on this problem
    > for
    > two days now :(
    Check the compareFunctions here
    http://flexdiary.blogspot.com/2008/09/groupingcollection-example-featuring.html

  • How can I sort my collection who bought what.

    Hi All,
    Dilema Music from 3 different users purchased on different apple accounts,all in one Mac, now we all live in seperate places and the music from the other 2 are no longer authorised. I want a way to find only the tracks of those users and delete them form a very large library approx 1.5TB. How can I organise this. So far I have a smart playlist of just "purchased AAC" files but am unable to figure out who bought what, Unless I go thru each item info then delete each one. There has to be a better way......

    Use this script -> Track Down Purchases v1.1
    "This script will examine each track in a selection of tracks or a selected playlist to determine if it was purchased from the iTunes Store and then copies it to a discrete playlist named for the person who purchased it, eg: "Steve Ballmer's Purchased Music". Recognizes song, video, and audiobook purchases. "

  • Collection sort

    Hi every body I have a small problem in sorting .
    I am taking one collection of type string .When I am sorting I is giving me wrong result.
    Here is my code :
    List <String> caps = new ArrayList<String>();
    caps.add("Alpha");
    caps.add("Beta");
    caps.add("alpha1");
    caps.add("Delta");
    caps.add("theta");
    Collections.sort(caps);It is sorting like :
    Alpha
    Beta
    Delta
    alpha1
    theta.
    Here I can take ant type of string even upper case / lower case .
    But the lower case words are coming later .
    Please help me out.
    thanks ,
    S

    default string sorting is case sensitive. if you want case insensitive sorting, do Collections.sort(caps, String.CASE_INSENSITIVE_ORDER)

Maybe you are looking for

  • APEX 4.2 and POI3.9 on Oracle 11.1.0.7.0

    Dear Experts, Currently we want to export a result set to Excel file in xlsx format. The approach we followed is to use Apache POI3.9 and we couldn't get the java file complied correctly. I could get the java file complied locally where we have the d

  • ITunes can't access a key?

    Hi When I try to install iTunes on my computer, this message pops up: Error 1402.Could not open key: HKEYLOCALMACHINES\Software\Classes\.cdda\OpenWithProgids. Verify that you have sufficient access to that key. I don't know how to verify that I have

  • Use operation in detail stamp

    Hi!! I am using jdeveloper 11.1.1.5 I had dragged and dropped departmentVO as af:table I had also dragged and dropped EmployeeVO in my DetailStamp of my af:table. While doin so I have an arrow occurs on the left side of my table if i clck the arrow i

  • Javafx 2.1: TableView CSS Removal Question

    Hi all i was hoping someone would be able to advise me on a query as regards TableView CSS. I have a tableView, inside of which i have a CellFactory to render my data. Inside of which i have the following condition check. That when found true i want

  • How to configure PI for WSS

    scenario: PI 7.0 Idoc-> PI > Soap i want to enable message level sec....i choose WSS, what are the set of steps i need to get done? Any inputs wud b greatly appreciated! Hank