Sort an an arrayList by the first element of an array

Hi,
I am really struggling trying to sort an arratList of arrays. I have an arrayList
ArrayList<String[]> myArrayList = new ArrayList<String []>(100);
Within this array I have may arrays with 2 elements
String[] myArray1 = {"Peter", "London"};
String[] myArray2 = {"John", "London"};
String[] myArray3 = {"Tony", "Birmingham"};
I add all these arrays to the arrayList and want to sort by the first element of the array. Basically I expect the final arrayList to be in the order of:
"John", "London"
"Peter", "London"
"Tony", "London"
Thanks
Peter

Hi,
I am really struggling trying to sort an arratList of
arrays. I have an arrayList
ArrayList<String[]> myArrayList = new
ArrayList<String []>(100);
Within this array I have may arrays with 2 elements
String[] myArray1 = {"Peter", "London"};
String[] myArray2 = {"John", "London"};
String[] myArray3 = {"Tony", "Birmingham"};
I add all these arrays to the arrayList and want to
sort by the first element of the array. Basically I
expect the final arrayList to be in the order of:
"John", "London"
"Peter", "London"
"Tony", "London"
Thanks
PeterThis can be done by using
Collections.sort(myArrayList, new Comparator<String[]>() {
public int compare(String[] s1, String[] s2) {
if (s1.length() <1) {
return -1;
if (s2.length() <1) {
return 1;
return s1[0].compareTo(s2[0]);
});

Similar Messages

  • ArrayList drops the first element

    I hate asking for help, but this has me confused.
    I have a code that outputs the elements of an arraylist as text strings to a file. For some reason, the first element of the ArrayList gets dropped, but every other element after gets saved to text perfectly.
    public void writeOut(ArrayList a)throws IOException{
        String[] out=new  String[a.size()];
        for(int i=0;i<out.length;i++){
            out=a.get(i).toString();
    System.out.println("" + out[i]); //test line to see if element has been moved
    I have also tried:
    public void writeOut(ArrayList a)throws IOException{
        String[] out=new  String[a.size()];
        for(int i=0;i<out.length;i++){
            out=(String)a.get(i);
    System.out.println("" + out[i]); //test line to see if element has been moved
    The code is straight forward, the best I can tell...so what am I overlooking? I am assuming that my array needs to be primed or something first. I suppose I could make the array one bigger and put some bogus value in the first element...That doesn't really seem the right way to do it though.

    I didn't notice it either until I tried to pass it an ArrayList with only one string....I must be having a problem where the ArrayList is being created then.
    And that is exactly where the problem was... :sigh:
    Thanks for checking that for me.

  • WebService problem: only the first element of a string array is returned

    Hello,
    i did the J2EE QuickCarRental tutorial and extended it by some features: I created another entity bean and implemented four new methods in the QuickOrderProcessor. Then i deployed it as a WebService and accessed it using the Visual Composer.
    Everything works fine except the return value of one WebService method. I created a method with the return value String[]. But the Visual Composer reads it as String. Only the first element of the resulting string array is displayed. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the whole string array with all its elements. What did i wrong?
    Another problem is that after deploying the J2EE-Application with new WebService methods the changes are not visible inside the visual composer. Although the test at the web-page http://<server>:<port>/QuickCarRentalService/Config1 displays the changes. Do i have to restart the WebService system in the portal content? If yes how can i do that?

    Here are details about setting up and using web services and some examples:
    /people/prakash.darji/blog/2006/10/10/external-web-service-proxy-configuration-for-visual-composer

  • Is it possible to bind the first element in a collection in a datagrid?

    I have a datagrid and I need to bind a property in the first element of the collection of my datasource object. By the momento I am using a converter:
    <DataGridTextColumn Header="MyValue" Binding="{Binding Converter={StaticResource myConverter}}"/>
    But I would like to avoid the need to use a converter, so I have tried this:
    <DataGridTextColumn Header="MyValue" Binding="{Binding MyCollectionProperty.ElementAt(0).MyValue}"/>
    Is there any way to do it?

    You cannot call ElementAt(i) from the XAML because it is a method.
    MyCollectionProperty[0] will certainly get you the first value of the MyCollectionProperty collection provided that the type has an indexer.
    If you want to be able to this without using a converter you must change the type of the property from ICollection<T> to for example IList<T>.
    You could create a wrapper property (potentially in a partial class definition) and bind to this one:
    //old property:
    public ICollection<YourType> MyCollectionProperty {
    get;
    set;
    //new wrapper:
    public IList<YourType> MyCollectionPropertyWrapper {
    get {
    return new List<YourType>(this.MyCollectionProperty);
    <DataGridTextColumn Header="MyValue" Binding="{Binding MyCollectionPropertyWrapper[0].MyValue}"/>
    ICollections are not very XAML friendly and you cannot bind to the first item of an ICollection using an indexer or ElementAt(0) or any other direct way.
    Please remember to mark all helpful posts as answer to close your threads.

  • Creating XML from XSD, Only create The First Element

    Hi,
    I create a XML File from a xsd schema by this way:
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              factory.setNamespaceAware(true);
              factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE,W3C_XML_SCHEMA);
                   factory.setAttribute(JAXP_SCHEMA_SOURCE, new File(MY_SCHEMA));   
                    DocumentBuilder documentBuilder =factory.newDocumentBuilder();
              documentBuilder.setErrorHandler(new SimpleDOMHandler());
              Document parse = documentBuilder.parse(new File(MY_XML));The first lines of the schema:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
         targetNamespace="http://gencat.net/scsp/esquemes/peticion"
         elementFormDefault="qualified" attributeFormDefault="unqualified"
         id="Peticio" xmlns:p="http://gencat.net/scsp/esquemes/peticion">
         <xs:element name="Apellido1">
              <xs:simpleType>
                   <xs:restriction base="xs:string">
                        <xs:maxLength value="40" />
                   </xs:restriction>
              </xs:simpleType>
         </xs:element>
         <xs:element name="Apellido2">
            .............................The problem is that the created document only have the first element "Apellido1". I dont know if it is a wrong xsd, or i'm using a bad way to do it.
    Thanks a lot, and apologize for my english

    Hi,
    Is it possible to create and populate XML from an XSD
    without knowing what the XSD elements are beforehand
    (all the examples appear to know what the input XSD
    will be, and therefore know what the set and get
    methods should be called)? I think it is possible--you would have to recompile each time (unless you can dynamically recompile, which would be neat), but using the classes getMethod() function, you can list all the methods. You would then have to do some tricky logic to determine which of the getMethods you want (for example NOT getClass()), and you can basically call them in sequence. You also need to worry about handling lists & recursively call xxxType classes.
    I'm experimenting with this, and it can get a little frustrating because there are a lot of odd cases to handle (for example, while setting the elements of a list, you need to actually get the list & add elements to it), but I think it's possible.
    >
    Can a user browse for an xsd to input, and the java
    will dynamically create the get methods, and be able
    to create instances and populate variables before
    converting to XML?
    What I'm puzzled about is where you'd get the data to populate the variables? Perhaps a database, or a bean? If you just want to make a test xml file, then it doesn't matter, but with real data, I think you'd still have to change how you actually get the variables you want to populate the xml file with, right? In other words, if your schema changed, the parameters you're passing to the set methods would change as well.
    Maybe we'll see some more packages in the future to make this task easier.

  • Message Mapping: Map value from the first element in a context in target el

    Hi experts,
    I have a problem with a message mapping in XI. I hope you can help me. At first I will give you a source and a target structure. Then I will explain the problem.
    <u>Source structure:</u>
    <E1EDP01>
       <E1EDPT1>
          <TDID> ... </TDID>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
       </E1EDPT1>
    </E1EDP01>
    The structure can contain more than one E1EDP01-Elements, more than one E1EDPT1-Elements and more than one E1EDPT2-Elements.
    <u>target structure:</u>
    <LineItem>
       <vendmemo> ... </vendmemo>
    </LineItem>
    For every E1EDP01-Element my mapping creates one LineItem-Element in the target structure. To fill the element <vendmemo> the mapping should do the following steps:
    The mapping should search in E1EDP01 for a E1EDPT1 with the TDID = Z505. And from this E1EDPT1-Element (with the TDID=Z505) the mapping should take the value <TDLINE> from the first E1EDPT2-Element in the context of the E1EDPT1-Element (the E1EDPT1 with the TDID=Z505) and put this value in <vendmemo>.
    The mapping should do this action for every E1EDP01 -> so for every LineItem.
    I tried it with UDF but I didn't found a solution. Can anybody help me?
    best regards
    Christopher

    Hello experts,
    i was wrong ... my mapping isn't still working. I had created a test instance. and only for this test instance the mapping (see above) works.
    Can anybody help me? I'm trying the whole day but I can't find a solution. Here a second description of my problem:
    <u>Source Structure:</u>
    <E1EDP01>
       <E1EDPT1>
          <TDID> ... </TDID>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
       </E1EDPT1>
    </E1EDP01>
    <E1EDP01>
       <E1EDPT1>
          <TDID> ... </TDID>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
          <E1EDPT2>
             <TDLINE> ... </TDLINE>
          </E1EDPT2>
       </E1EDPT1>
    </E1EDP01>
    <u>Target Structure:</u>
    <LineItem>
       <vendmemo> ... </vendmemo>
    </LineItem>
    <LineItem>
       <vendmemo> ... </vendmemo>
    </LineItem>
    <u>Description of my Problem:</u>
    For each E1EDP01 in the source structure the mapping creates one LineItem in the target structure.
    The element "vendmemo" should be created in any case ... also if it will be empty.
    To fill the element "vendmemo" the mapping should search in E1EDP01 for a E1EDPT1 with the TDID=Z505. If there is an element E1EDPT1 with the TDID=Z505, the mapping should write the TDLINE from the first E1EDPT2 (under the element E1EDPT1 with the TDID=Z505) in the target field "vendmemo".
    The Problem is that TDLINE an TDID are not in the same context. I tried it with setting the context of both to E1EDP01. But it was not working ... have you any idea oder suggestion?
    Thank you very much
    best regards
    Christopher

  • How to get the first element of a List?

    Hi,
    I have the following hierachy:
    A (top level)
    -A1 (child of A)
    -B1 (child of A)
    --B11 (child of B1)
    --B12 (child of B1)
    I have an UDA on members B11 and B12 that have the same name as A1, and I use it to allocate values from A1 to B11 and B12. After that I want to aggregate the hierachy so I can have B1 and A with values.
    I would like to use the ancestors function to do that but Ancestors need a member as parameter and the only relation between A1 and B11 and B12 is the UDA.
    I can't do @ANCESTORS(@UDA(dimName, "A1")) because of that, so I would like to use a function to get at least 1 member that has the UDA I want and to use Ancestors on it, however I can't seem to find a function that returns the first member of a List.
    Can someone help me on this?
    Thank you

    Unfortunately it doesn't work. @List requires members names so I can't provide a member set as an argument :(^^^Are you sure? Take a look at the below example from the Tech Ref. That sure looks like @LANCESTORS and @LIST is accepting more than just member names.
    FIX(@LANCESTORS(@LIST(@ATTRIBUTE(Caffeinated_True),@ATTRIBUTE(Ounces_12),"200-40")))Also note this:
    If the @LANCESTORS function is used alone (not within a FIX statement), you must use the @LIST function and specify member names. So you DO have to use @LIST if @LANCESTORS is to be used to do an aggregation. Or so it appears.
    Regards,
    Cameron Lackpour

  • BindAggregation only returning the first element from a XML node

    hello everyone,
    investigating on this issue since fiew hours, I need your help (did not find a similar issue).
    here is an xml sample:
    <users>
         <user active="true">
              <reference/>
              <name>
                   <prefix/>
                   <first>first</first>
                   <middle/>
                   <last>last</last>
              </name>
              <location></location>
              <identifier>
                   <domain>mydomain</domain>
                   <login>flast</login>
              </identifier>
              <email>
                   <address>[email protected]</address>
                   <type>text</type>
              </email>
              <roles>
                   <role name="A"/>
                   <role name="B"/>
                   <role name="C"/>
                   <role name="D"/>
                   <role name="E"/>
                   <role name="F"/>
                   <role name="G"/>
              </roles>
              <groups>
                   <group name="A1"/>
                   <group name="A2"/>
              </groups>
         </user>
    </users>
    After having set the data in the table:
    oModel.setData(data);               
    oTable.setModel(oModel);
    oTable.bindRows("/user");
    I am able to bind correctly properties like first name & last name in my table... but I am not able to do a bindAggregate on roles !
    When I do this, only the first role is returned everytime for each row.
    With the example above,
    It displays, : first as firstname, last as lastname, & only role A instead of displaying all roles from A to G as above in the xml.
    Here is the bindAggregation:
    oTable.addColumn( new sap.ui.table.Column({
         label: new sap.ui.commons.Label({text: "Roles"}),
         template: new sap.ui.commons.ListBox({  
              "items": {     
                   path: "roles",
                   template: new sap.ui.core.ListItem({text: "{role/@name}",})
    Where is my misunderstanding/mistake ? or how should I deal for having all roles displayed correctly in the listbox of this column ?
    No proposal ?
    Files (javascript & data) for reproducing this behavior are attached below,
    Really thank's in advance to each of you for your coming help,
    Best Regards

    hello everyone,
    investigating on this issue since fiew hours, I need your help (did not find a similar issue).
    here is an xml sample:
    <users>
         <user active="true">
              <reference/>
              <name>
                   <prefix/>
                   <first>first</first>
                   <middle/>
                   <last>last</last>
              </name>
              <location></location>
              <identifier>
                   <domain>mydomain</domain>
                   <login>flast</login>
              </identifier>
              <email>
                   <address>[email protected]</address>
                   <type>text</type>
              </email>
              <roles>
                   <role name="A"/>
                   <role name="B"/>
                   <role name="C"/>
                   <role name="D"/>
                   <role name="E"/>
                   <role name="F"/>
                   <role name="G"/>
              </roles>
              <groups>
                   <group name="A1"/>
                   <group name="A2"/>
              </groups>
         </user>
    </users>
    After having set the data in the table:
    oModel.setData(data);               
    oTable.setModel(oModel);
    oTable.bindRows("/user");
    I am able to bind correctly properties like first name & last name in my table... but I am not able to do a bindAggregate on roles !
    When I do this, only the first role is returned everytime for each row.
    With the example above,
    It displays, : first as firstname, last as lastname, & only role A instead of displaying all roles from A to G as above in the xml.
    Here is the bindAggregation:
    oTable.addColumn( new sap.ui.table.Column({
         label: new sap.ui.commons.Label({text: "Roles"}),
         template: new sap.ui.commons.ListBox({  
              "items": {     
                   path: "roles",
                   template: new sap.ui.core.ListItem({text: "{role/@name}",})
    Where is my misunderstanding/mistake ? or how should I deal for having all roles displayed correctly in the listbox of this column ?
    No proposal ?
    Files (javascript & data) for reproducing this behavior are attached below,
    Really thank's in advance to each of you for your coming help,
    Best Regards

  • Comparing an element of an array with the previous element in that array.

    First post, please let me know if there's anything I should do differently.
    I'm grabbing a scope measurement in the form of a triangle waveform, and want only the parts of it with a positive differential - essentially a sawtooth. The waveform is stored in a one-dimensional array. Also, there is no way for me to trigger the measurement, so there is likely an incomplete bit of waveform before the first lowest value.
    To prepare the data I decided to do two things:
    -Cycle through the array and delete everything until I find the first lowest value.
    -Save the values from lowest to highest, then delete everything until the next lowest value. Do this n times.
    Does anyone have any good examples of cycling through an array in such a manner, or is there simply an easier way of going about it?

    Thank you very much for the response!
    Unfortunately I don't have any code to post at the moment, but you can assume the input would be an array of voltage values that comprise a triangle wave. Good suggestion about the array min/max function, however I forsee a potential issue with it.
    It's possible that the triangle wave won't be 'perfect.' That is, the voltage of one peak or valley might not be exactly identical as measured from one to the other. It would be really nice if I could count on them to be identical, then I could min/max and just search for the min and max values. If I min/max, it's possible I could come up with a point at the middle or end of my waveform and lose useful data before it. There are two likely scenarios for the start of the waveform, so...
    -We start on the downward slope of the triangle wave somewhere in the middle of it.
    if array[x+1] is less than array[x], delete array[x]. If it's not, exit the loop.
    -We start on the upward slope of the triangle wave somewhere in the middle of it.
    This one is tougher. I could use Min/Max and make the determination based on how close to the min value we are within some margin of error.
    -We could start exactly on the peak or valley of the triangle, but this is very unlikely with the number of measurements taken.
    Is there a min/max that would allow for some margin of error?

  • Displaying the sorted acct number as the first element

    Hi,
    I have list of account numbers , say 5 account numbers (2300,5200,7689,1234,4566) from which I found which is the parent acct number by invoking a query. Here the parent acct number is say "1234". Now i need to make sure that parent acct number records should always display at the top part of the screen followed by other child acct numbers displayed in ascending order. Here my question is, having found the parent acct no (1234) , how I can make sure this will be displayed at the top. Because the final list contains other acct numbers as well. Using comparator is a pbm. as i cannot pass the parent acct no to the compare() method to display this at the top. I want to do this in a single final list itself which contains all the acct number details. How to go about this? Please shed some light into this.
    Thanks.
    JavaCrazy

    Re: Sorting the respective account number at the top
    What happened to this thread?

  • How to sort a 2 dim. array by the first column?

    Hi there,
    I need to know, how to sort a 2 dim. String array by the first column, which means "string[0][x]".
    I think, I have to implement a new comparator class. But how?
    Thanks in advance for any help

    I need to know, how to sort a 2 dim. String
    array by the first column, which means
    "string[0][x]".You want to sort the array using the first element in each row and that element is a String?
    Let's forget about generics. Say you want to supply a Comparator. The compare method should decide the order between elements when passed two element objects. In a two-dimensional array the elements will be one-dimentional arrays and you use the first element in those arrays, like
    public int compare(Object s1, Object s2) {
       String[] a1 = (String[]) s1;  // first row array
       String[] a2 = (String[]) s2;  // second row array
       return a1[0].compareTo(a2[0]); // compare first element of row arrays
    }

  • Can I sort on the second element of my vector?

    Sorry to intrude on the guru territory, but no one in the newbie camp has answered and I am sure someone over here has a quick answer...
    The first element is first name and the second is lastname. Right now I am using java.util.Collections.sort(v); This searches on the first name. I would like to search on the last name which is the second element. Any ideas?

    I'm not sure what's in your vector. I assume the vector contains strings, of the form "firstname lastname". In which case I suspect the default implemetation of sort is simply sorting the strings in the natural way. If you look at the second implementation of sort():
    sort(List l, Comparator c)
    you can implement your own comparator. The comparator is an interface tast you implement to compare two object the way you want th sorting done.
    so your comparator would implement compare to find the second word of each string (look at string tokenizer for this) and compare them (with String.compareTo). You need to do something similar with equals.
    So you call sort like this: sort(myVector,new MyComparator());
    Hope this helps.

  • Can I sort by the second element in my vector?

    The first element is first name and the second is lastname. Right now I am using java.util.Collections.sort(v); This searches on the first name. I would like to search on the last name which is the second element. Any ideas?

    Write a subclass of Comparator that looks at the second element, and give an instance of it to the sort method along with the array.

  • How can I append to an array of defined length and have the first value added be the first value out.

    I want to build/append to an array. Let's say the length is defined at 10 elements. When the 11th element comes in I want the first element to be kicked out so that the array always has the most recent 10 elements in it in order. the arrays should look like this:
    {0,1,2,3,4,5,6,7,8,9}
    {1,2,3,4,5,6,7,8,9,10}
    {2,3,4,5,6,7,8,9,10,11}
    etc.
    Any help is greatly appreciated. Thanks 
    Solved!
    Go to Solution.

    Here's a revised VI, except I'm using LV8.5 and the lowest I can save down to is 8 so perhaps someone will be kind enough to convert this?
    Attached an image too
    Message Edited by Sima on 01-13-2009 06:14 PM
    Attachments:
    rotatearray[1].vi ‏14 KB
    rotatearray[1].JPG ‏66 KB

  • NXSD is missing first element

    Hi ,
    When I test the nxsd generated I see the first element is being used for differentiating the records and it is missing from the output xml.But I want that to appear in the output xml.
    I treid modifying the nxsd to include c1 element manually it didn't helped.
    <xsd:choice minOccurs="1" maxOccurs="unbounded" nxsd:choiceCondition="fixedLength" nxsd:length="4">
            <xsd:element name="RECORD1" nxsd:style="array" nxsd:cellSeparatedBy="${eol}" nxsd:conditionValue="P03A">
              <xsd:complexType>
                <xsd:sequence>
                  <xsd:element name="C2" type="xsd:string" nxsd:style="fixedLength" nxsd:length="3" />
    C1 elements declaration is missing from the generated nxsd. I am expecting the value "P03A" to be present in the output xml,during the initial config of nxsd I used these 4 characters to differentiate the records.My records have data PO3A,P03B etc...where the 4th character is the differentiator.The data is being used for identifying the different records in the flat file and it is not appearing in the output xml.

    This is most probably because the Periodicity input value has been configured as "Required" and no value has been input for it.
    Please enter a value and try to re-run Quick Pay.

Maybe you are looking for