Structure of arrays sort

Hi, I have a structure of arrays as follows.
The Structure is session.cart
my arrays are session.cart.foodname[ ]
session.cart.comments[ ]
session.cart.name[ ]
session.cart.price[ ]
All of these arrays correspond to each other, so
session.cart.name[1] may be John, who ordered a cheeseburger
(session.cart.foodname[1]). So i need to sort these by the persons
name and have the other 3 arrays sort with them, so they still
correspond to each other. Can anyone help me with this? Ive looked
over the structsort function but cant figure out how to apply it to
a structure of arrays. Thanks for the help.

I would avoid using multiple arrays, which have to refer to
each other - without really having a proper way to execute the
plan. Structures are better for this. I created an example, which
you might try out, and see if it fits your needs:
<cfscript>
session.cart.item = structnew();
// use the name also as a key
session.cart.item["john"]=structnew();
session.cart.item["john"]["name"] = "john";
session.cart.item["john"]["foodname"] = "Ribs";
session.cart.item["john"]["price"] = "13.99";
session.cart.item["john"]["comments"]="Johncomment";
session.cart.item["mary"]=structnew();
session.cart.item["mary"]["name"] = "mary";
session.cart.item["mary"]["foodname"] = "Apple";
session.cart.item["mary"]["price"] = "0.49";
session.cart.item["mary"]["comments"]="Marycomment";
session.cart.item["adam"]=structnew();
session.cart.item["adam"]["name"] = "adam";
session.cart.item["adam"]["foodname"] = "Cake";
session.cart.item["adam"]["price"] = "4.99";
session.cart.item["adam"]["comments"]="Adamcomment";
// the following line actually does all you ever wanted.
arrayToList() is just a bonus
// for easy-to-understand-output in the end. More elegant
solutions may exist. :-)
nameList =
arrayToList(structSort(session.cart.item,"textnocase","asc","name"));
</cfscript>
<cfoutput>
<cfloop list="#nameList#" index="currentName">
#session.cart.item[currentName].name#<BR>
#session.cart.item[currentName].foodname#<BR>
#session.cart.item[currentName].price#<BR>
#session.cart.item[currentName].comments#<BR>
<HR>
</cfloop>
</cfoutput>

Similar Messages

  • Structures in Arrays + sorting

    Hi,
    i want to do some sorting on a structure where the items will
    get rearranged like arraysort does, and not give me the a sorted
    list of keys.
    So I did an array that contains structures. I also wanted to
    use structures because i wanted to use names instead of numbers for
    referencing my data.
    so here's my code.
    <CFSET myArray = arrayNew(1)>
    <CFSET myStruct = structNew()>
    <CFSET myStruct.item = "1">
    <CFSET arrayAppend(myArray, myStruct)>
    <CFSET myStruct = structNew()>
    <CFSET myStruct.item = "2">
    <CFSET arrayAppend(myArray, myStruct)>
    <CFSET arraySort(
    myArray.item, "numeric", "ASC")>
    how can i make this work?

    You could store the data as a query instead of an array of
    structures. That would give you access to CF's native query
    sorting.

  • Sort values of structure with arrays

    Hi
    For a shopping cart I'm using a structure with arrays to store the items in the cart. I tried to use StructSort but did not work...
    This is how I store the items in the cart:
    <cfscript>
                if (not(isdefined("session.cart"))) {                // Check to make sure that the Shopping cart structure exists.
                    session.cart = structnew();
                // The item structure we are going to use to store the items in the cart
                // is going to have four parts...
                //         1.  The item id
                //         2.  The item name
                //         3.  The price per unit
                //         4.  The quantity
                tempvalue = listtoarray('#attributes.id#,#attributes.name#,#attributes.price#,#attributes.quantity#') ;
                // if the item is not yet in the cart, simply add it to the cart
                if (not(structKeyExists(session.cart, attributes.name))) {
                    StructInsert(session.cart,attributes.name,tempvalue);
                // if the item is already in the cart, update the item quantity
                else {
                    tempvalue[4]=session.cart[attributes.name][4]+attributes.quantity;
                    StructUpdate(session.cart,attributes.name,tempvalue);
    </cfscript>
    Any help will be appreciated.
    Thank you.
    TJ

    To loop over an array one has two options:
    <cfloop index="i" from="1" to="#arrayLen(a)#">
    Or:
    <cfloop index="someVar" array="#a#">
    Personally I use the former because I think the implementation of array-looping with <cfloop> is cocked-up as it's not the index that gets put into "someVar", it's the array element itself.  So by way of pedantic protest, I don't use that syntax.
    But anyway...
    The reason why your struct is unordered is because structs are - innately, and by definition - unordered.  If you want an ordered data structure, you use an array.
    However what you are wanting to do is to sort your array by a subkey value of the structs the array contains.  If you want to do that, you will need to roll your own sorting solution.
    Personally I'd stick with using an array and just use its intrinsic ordering (the order in which items are added to it).  However if you wanted to sort on one of the inner struct keys, you could maintain a separate struct keyed on the value you wish to sort on, containing a reference to the array element in the original array.  Then you could extract a structKeyArray() from that, and use arraySort() to order those index keys in whichever order you like.
    Adam

  • Array sort with objects?

    hits = searcher.search(query);
    //java.util.Vector sortHits = new java.util.Vector ();
    int[][] sortHits = new int[hits.length()][1];
    // assign values to array
    int teller = 0;
    for (int i = 0; i < hits.length(); i++)
         Document doc = hits.doc(i);
         String absnumtxt = doc.get("absnumtxt");
         if(sAllCookies.indexOf(absnumtxt) >= 0){
              sortHits[0] = Integer.parseInt(absnumtxt);
              teller++;
              continue;
    But the method Arrays.sort(sortHits); causes a ClassCastException error. Somebody an idea to solve this?
    The structure is:
    sortHits[0][0] = 2
    sortHits[1][0] = 0
    sortHits[2][0] = 0
    sortHits[3][0] = 0
    sortHits[4][0] = 0
    sortHits[5][0] = 0

    A two-dimentional array is an array of array of something.
    Sorting a two-dimentional array requires a Comparator, because you compare uni-dimentional arrays, and arrays are not naturally comparable.
    (BTW, why declaring a two-dimentional array here? you set the second dimention length to 1... a simple array would make it, no?)

  • Doubt in working of Arrays.sort method. help needed !!!!

    Hello Friends,
    I am not able to understand output of Arrays.sort method. Here is the detail of problem
    I wrote one program :
    public static void main(String[] args) throws ClassNotFoundException
         Object[] a = new Object[10];
         a[0] = new String("1");
         a[1] = new String("2");
         a[2] = new String("4");
         a[3] = new String("3");
         a[4] = new String("5");
         a[5] = new String("20");
         a[6] = new String("6");
         a[7] = new String("9");
         a[8] = new String("7");
         a[9] = new String("8");
    /* Sort entire array.*/
         Arrays.sort(a);
         for (int i = 0; i < a.length; i++)
         System.out.println(a);
    and output is :
    1
    2
    20
    3
    4
    5
    6
    7
    8
    9
    Question : Does this output is correct? If yes then on which basis api sort an array? I assume output should be 1 2 3 4 5 6 7 8 9 20.
    Can here any one please explain this?
    Thanks in advance.
    Regards,
    Rajesh Rathod

    jverd wrote:
    "20" and "3" are not numbers. They are strings, and "20" < "3" is exactly the same as "BA" < "C"The above is
    ... quote 20 quote less than quote 3 quote...
    but shows up as
    ... quote 20 quote less than quote...
    Weird.

  • Pass structure or array into a custom tag?

    Is it possible to pass a CF structure or array to a custom
    tag (C++/MFC) as an argument? Is it possible to create a CF array
    or structure *from* a custom tag?

    Passing a structure out is as easy as using a period in the
    variable name in your SetVariable() call.
    For example,
    pRequest->SetVariable ("SPP_zResults.bHadErroredPts", "0");
    pRequest->SetVariable ("SPP_zResults.dMax",
    "3.14159265");
    Passing a struct in may be just as easy, I haven't ever
    needed to try it.
    Let us know if it works.

  • Arrays.sort() issue when Numbers are a string!

    Hey guys -- here is my problem.
    I am working on a TOP TEN SCORES mechanism for a trivia game. I have read in the score and the players name from a file. SO I have 2 different arrays topScores[] and topNames[] ---
    Now if someone plays the game and has a higher score than the lowest score, they get to put their score and name in the file and replace the low score.
    HOWEVER -- I do not know how to sort topSCORES[] and then make whatever sorted changes apply also to the topNAMES[] array.
    SO I thought - HEY I will concatenate the topScores and topNames into a single String array. And then SORT! This sounded like a great idea until I realized that the following will happen:
    100 tvance (first one)
    1000 dvance (second score)
    250 danderson (third score) !!!
    See my problem? When I sort this way - it is sorting alphabetically so it will put a 1000 score before a 200-900 score! ---
    **I hope I explained this adequately -- can someone help? Is there a way to sort the topScores array and have it also change the order of the topNames array as well?

    Create a new class - HighScore, which has a highScore and a name?Yup. This technique even has a name: object-oriented programming!
    Demo:
    import java.util.*;
    public final class HighScore implements Comparable<HighScore> {
        private final int score;
        private final String name;
        public HighScore(int score, String name) {
            if (name == null)
                throw new NullPointerException();
            this.score = score;
            this.name = name;
        public int getScore() {
            return score;
        public String getName() {
            return name;
        public int compareTo(HighScore that) {
            if (this.score < that.score)
                return -1;
            else if (this.score > that.score)
                return +1;
            else
                return this.name.compareTo(that.name);
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            else if (obj instanceof HighScore) {
                HighScore that = (HighScore) obj;
                return this.score == that.score && this.name == that.name;
            } else
                return false;
        public int hashCode() {
            return score ^ name.hashCode();
        public String toString() {
            return score + " " + name;
        //demo
        public static void main(String[] args) {
            HighScore[] top = {
                new HighScore(250, "danderson"),
                new HighScore(1000, "dvance"),
                new HighScore(100, "dvance")
            Arrays.sort(top);
            for(int i=0; i<top.length; ++i) {
                System.out.println(top);
    If you are using an older version of Java (1.4 or earlier), the generics won't be
    recognized. In that case the class definition would begin:
    public final class HighScore implements Comparable {And the compareTo method would begin:
    public int compareTo(Object obj) {
        HighScore that = (HighScore) obj;Good luck!

  • Java.util.Arrays.sort for Vector

    I used the java.util.Arrays.sort to sort an array based on the method below.
                  java.util.Arrays.sort(array, 0, total, new ComparatorX());
               repaint();
                class ComparatorX implements java.util.Comparator
              public int compare( Object p1, Object p2){
                   int x1=((Point)p1).x;
                   int x2=((Point)p2).x;
                   if(x1>x2)
                                return 1;
                   if(x1>x2)
                                return -1;
                   return 0;
         }I've since changed the array to a vector. Is there anyway I can keep the comparator. Or how can I sort the vector based on the above method.

    BTW: Don't know if it's just a typing mistake, but your code contains an error:
    class ComparatorX implements java.util.Comparator     {
       public int compare( Object p1, Object p2) {
          int x1=((Point)p1).x;
          int x2=((Point)p2).x;
          if (x1>x2) {
             return 1;
          if (x1>x2) {  // Should be: if (x2 > x1) ...
             return -1;
          return 0;

  • TreeSet vs Collection.Sort / Array.sort for Strings

    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunch

    SpaceShuttle wrote:
    Gurus
    I am pondering weather to use TreeSet vs the Collections.sort / Array.sort for sorting Strings.
    Basically I have a list of Strings, i need to perform the following operations on these Strings
    1) Able to list Strings starting with a Prefix
    2) Able to list Strings Lexically greater than a String
    Any help would be greatly appreciated!
    Thanks a bunchBig-O wise, there's no difference between sorting a list of N elements or inserting them one by one in a tree-set. Both take O(n*log(n)). But both collections are not well suited for looking up string that start with a certain substring. In that case you had better use a Patricia tree (or Radix tree).
    Good luck.

  • Relate to Array.sort(), urgent help~~

    I am using a class for store the data
    then I need to sort them
    is it the vector which want to sort is needed in same class???
    because I use other file to access them~~
    The following code:
    public Test()
    Person person;
    Vector v = new Vector();
    v.add(new Person("Johnson","Fox");
    v.add(new Person("Johnson","David");
    Object[] a = v.toArray();
    Arrays.sort(a);
    public int compareTo(Object dd,Object ww)
    if (dd instanceof Person && ww instanceof Person)
    Person d = (Person) dd;
    Person w = (Person) ww;
    return w.lname.compareTo(d.lname);
    else
    return 0;
    the code doesn't work btit can compile, can anyone help me to solve it??
    thank you for your time~~

    In Person.java use the following:
    class Person
       public int compareTo(Object cmpPerson)
          if (cmpPerson instanceof Person)
             return this.lname.compareTo( ((Person)cmpPesron).lname );
          else
             return 0;
    }

  • Array.sort() question

    I've been looking at Arrays and the Comparator interface. But I don't understand the sorting results:
    import java.util.*;
    import java.io.*;
    class SearchObjArray {
         public static void main(String[] args) {
              Console con=System.console();
              if (con==null) System.exit(1);
              String[] sa={"one","two","three","four"};
              Arrays.sort(sa);          
              con.format("The sorted string:%n");          
              for(String s: sa)
                   con.format("%s ",s);
              //four,one,three,two
              con.format("%nA binary search for \"one\": one=%s%n",Arrays.binarySearch(sa,"one"));
              //one=1, as expected. The binarySearch found "one" in position 1 of the sorted array.
              ReSortComparator rs=new ReSortComparator();     
              con.format("A binary search for \"one\" using the resort comparator on the string array: one=%s%n",Arrays.binarySearch(sa,"one",rs));
              //one=-1<====WHY -1? Why is the insertion point 0?
         static class ReSortComparator implements Comparator<String> {
              public int compare(String a, String b) {
                   return b.compareTo(a);
              

    You have to search using the same ordering rules as how the array is sorted. You sorted with one set of rules (String's natural ordering) and searched with a different set of rules (the opposite ordering, as determined by your comparator). That's the same as trying to do a binary search on an unsorted array. Since one of the preconditions of binary search is that the array be sorted, it shouldn't be surprising that you get odd results.

  • Arrays.sort

    Why is the Arrays.sort method defined as
    public static void sort(Object[] a)
    instead of
    public static void sort(Comparable[] a) ?

    jverd wrote:
    This way we can sort an array whose elements are all mutually comparable, even if the array itself is not declared to be of a Comparable type. I can't think of a specific use case where that would be useful, but it's the only reason I can think of for deliberately making that decision.Dear jverd, I am not sure I understand the possible case you are referring to. I tried the following code and it gives a runtime Exception.
      public class ArraysTest {
        public static void main(String argsp[]){
            Data [] dr = new Data[4];
            dr[0] = new Data(4);        dr[1] = new Data(0);
            dr[2] = new Data(8);        dr[3] = new Data(3);
            Arrays.sort(dr);
            System.out.println(dr);
    class Data{
        Integer i;
        public Data(int j){
            i = j;
        public int compareTo(Data d){
            if(i<d.i)
                return -1;
            if(i==d.i)
                return 0;
            return 1;
        @Override
        public String toString(){
            return i.toString();
    }<font color="red">
    Exception in thread "main" java.lang.ClassCastException: temp.Data cannot be cast to java.lang.Comparable
    [Ltemp.Data;@b37c60d
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.sort(Arrays.java:1079)
    </font>

  • Multidimensional Array Sort

    Please help. I am very new to java and trying to build a multidimensional array. I have two variables 1)item_name and 2)item_value. These are values that I obtain by looping through a database result set. I need to build and array that can hold these variables. Once the multidimensional array is built I need to be able to sort it by item value.
    For example I would like to do something like this:
    while (rs.next)
    array.name = item_name
    array.value = item_value
    end
    array.sort(value)
    Thanks for any help!

    Don't use a multidimensional array. Use an array of objects, where the objects are of a class that you define. It might be something as simple as class Item that just has two fields--name and value--and their getters and setters. Or maybe just getters if you want the class to be immutable.
    Have the class implement Comparable and sort on value.
    If you sometimes want to sort on value and sometimes on name, then you'll need to either define two Comparators (one for name, one for value) or make the class Comparable on whichever is the more "natural" ordering and define a Comparator for the other one.
    Either put them in an array and use one of the java.util.Arrays.sort methods to sort them, or put them in a List (java.util.LinkedList or java.util.ArrayList) and use Collections.sort to sort them.

  • Array.sort(Object[], comparator) problems

    I have been trying for days to figure out how to sort my array of geneInfo ono the field score1.
    when i try to use Arrays.sort(gInfo, new score1Comp()) it turns all of the array null.
    class score1Comp implements Comparator
    public int compare(Object o1, Object o2)
    geneInfo g1 = (geneInfo)o1;
    geneInfo g2 = (geneInfo)o2;
    // added these checkers to get rid of nullPointerException, but checked to see that most are non null
    if(g1==null&&g2==null)
    return 0;
    if(g1==null)
    return -1;
    if(g2==null)
    return 1;
    if(g1.getScore1() == g2.getScore1())
    return 0;
    else
    double temp = g1.getScore1() - g2.getScore1();
    System.out.println("score g1 - score g2: " + temp);
    System.out.println("rounded: " + (int)Math.round(temp));
    return (int)Math.round(temp);
    public boolean equals(Object obj)
    return obj.equals (this);
    }

    You have sorting your array with null to be the least on value object. For example here:
    MyObject[] objs = new MyObject[1000];
    objs[0] = new MyObject(3);
    objs[1] = new MyObject(2);
    objs[2] = new MyObject(1);
    Arrays.sort(objs, new score1Comp());Guess what the result would be? Your array would have the first 997 elements become null and the last 3 would be sorted to (1), (2), (3).
    So the cause is how your Comparator treats the null value. The solution could be to make sure your sorting array is filled correctly, or reverse the return 1/-1 for the null treatment.
    --lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Java Array Sorting

    I am having problems sorting this array in ascending and descending order. I also need to intitialize a reset button.
    Thanks! :>)
    import java.util.*;
    import java.io.*;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Combine3 extends Applet implements ItemListener
    Label lblTitle = new Label("Sorting");
    Label lblTitle2 = new Label("Please select Sort option");
    CheckboxGroup chkItems = new CheckboxGroup();
    Checkbox chkAscending = new Checkbox("Ascending)", true, chkItems);
    Checkbox chkDescending = new Checkbox("Descending)", false, chkItems);
    Checkbox chkHidden = new Checkbox("",true,chkItems);
    Button btnSort = new Button("SORT");
         TextField txtOne = new TextField("-3");
         TextField txtTwo = new TextField("0");
         TextField txtThree = new TextField("5");
         //Textfield txtFour = new Textfield("33");
         //Textfield txtFive = new Textfield("23");
         //Textfield txtSix = new Textfield("1");
         //Textfield txtSeven = new Textfield("");
         //Textfield txtEight = new Textfield("-3");
         //Textfield txtNine = new Textfield("-3");
         //Textfield txtTen = new Textfield("-3");
    public void init()
         add(lblTitle);
         add(lblTitle2);
         add (txtOne);
         add (txtTwo);
         add (txtThree);
         add(chkAscending);
         add(chkDescending);
         add(btnSort);
         setBackground(Color.cyan);
         //     add(lblDisplay);
         chkAscending.addItemListener(this);
         chkDescending.addItemListener(this);
         //btnSort.addActionListener(this);
    /* public void actionPerformed(ActionEvent e) {
         chkHidden.setState(true);
    //Executed when checkbox is selected or unselected
    public void itemStateChanged(ItemEvent e) {
         //sort in ascending order
         String strInput;
         int intArray[] = new int[3];
         //for (int x=0; x<intArray.length; x++)
              strInput = txtOne.getText();
              intArray[0] = Integer.parseInt(strInput);
              strInput = txtTwo.getText();
              intArray[1] = Integer.parseInt(strInput);
              strInput = txtThree.getText();
              intArray[2] = Integer.parseInt(strInput);
         if (chkAscending.getState() == true)
         Arrays.sort(intArray);
         // display ascending order
         //for(int i=0; i<intArray.length; i++)
              txtOne.setText(" " + intArray[0]);
              txtTwo.setText(" " + intArray[1]);
              txtThree.setText(" " + intArray[2]);
         //lblTitle2.setText("Ascending: " + i + "Value: " + intArray);
         // sort in descending order
         else if (chkDescending.getState() == true)
    for (int i=intArray.length-1; i >= 0; i--)
              for(int j=1; j <= i; j++)
                   if (intArray[j-1] < intArray[j])
              int temp = intArray[j-1];
                   intArray[j-1] = intArray[j];
                   intArray[j] = temp;
                   } // end if
    } // end for
         } // end for
         // display descending order
         for(int i=0; i<intArray.length; i++)
         lblTitle2.setText("Descending: " + i + " Value: " + intArray[i]);
    } // end else if
    } //End itemStateChanged
    } //End Class

    You might take a quick look at the following link regarding sorting arrays. The "Arrays.sort(xxx)" mechanism works well.
    http://developer.java.sun.com/developer/TechTips/1999/tt0923.html

Maybe you are looking for

  • Creation of Recovery Disks - 'Failed to open the following file" Error

    Greetings All, I am in the process of trying to create a Recovery Disk Set for a Client's *Satellite L300 - PSLB8A-07U004*. While the application opens and begins the creation of the disk set, it has, three times now, failed at with the error message

  • Auto select hex number via color picker

    Hey everyone, Why is it that on some versions of cs6 when i select the "set foreground color" (or background), the color dialog pops up with the hex number selected allowing me to quickly ctrl+c it. However, on other computers - with the exact same c

  • Seprating Persistence logic from business logic

    Hi all !! I was thinking about that is there any known way or a possible way by which i can write a Entity Bean in which i can seprate the business logic and Persistence logic. Like what if i want to decide at the deployment type whether my Bean is g

  • Error with calendar

    Hi, experienced an error in the calendar. . Its actually off 1 day starting from 10 Nov till 31 Dec before its back to normal. Did u experience it as well?

  • Converting mp4 files to mp3 files

    could someone tell me how to convert mp4 files into mp3 files? thanks