Sort Collection

Hi,
How can I sort this collection ( by scode)? I am using oracle 8i. I have tried using code from:
http://technology.amis.nl/blog/?p=1217
but I am not able to get to work. Any help would be appreciated.
Thanks,
Ravi
v_source varchar2(20);
v_source_state char(1);
TYPE record_type is record (scode varchar2(20), scount number);
TYPE table_type is table of record_type index by binary_integer;
v_source1 table_type;
begin
for j in 1..10 loop
if j = 1 then
v_source := 'AEA';
elsif j = 2 then
v_source := 'ACA';
elsif j = 3 then
v_source := 'AAA';
elsif j = 4 then
v_source := 'ABA';
elsif j = 5 then
v_source := 'ABA';
elsif j = 6 then
v_source := 'ADA';
elsif j = 7 then
v_source := 'ADA';
elsif j = 8 then
v_source := 'AEA';
elsif j = 9 then
v_source := 'AEA';
elsif j = 10 then
v_source := 'AAA';
end if ;
---- AAA 2
---- ABA 2
---- ACA 1
---- ADA 2
---- AEA 3
if v_source1.count > 0 Then
v_source_state := 'N';
for i in v_source1.first..v_source1.last loop
if v_source1(i).scode = v_source then
v_source1(i).scount := v_source1(i).scount + 1;
v_source_state := 'Y';
end if;
if i = v_source1.count and v_source_state = 'N' then
v_source1(i+1).scode := v_source;
v_source1(i+1).scount := 1;
end if;
end loop;
else
v_source1(1).scode := v_source;
v_source1(1).scount := 1;
end if;
end loop;
for k in v_source1.first..v_source1.last loop
dbms_output.put_line('Source: '||v_source1(k).scode||' Count: '||v_source1(k).scount);
end loop ;
Edited by: joshiravi on Sep 29, 2008 9:40 AM

I have modifed my code but I am getting a error the following error (select statment):
Line # 89 Column # = 1 Error Text = PLS-00801: internal error[22914]
Line # 89 Column # = 1 Error Text = PL/SQL Statement ignored
Ref:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:14334298866128
New Code:
v_source varchar2(20);
v_source_state char(1);
TYPE record_type IS RECORD
(scode varchar2(20), scount number);
--TYPE table_type IS TABLE OF record_type INDEX BY PLS_INTEGER;
TYPE table_type IS TABLE OF record_type index by binary_integer;
v_sort_table source_sort_table := source_sort_table();
--v_index                           PLS_INTEGER;
v_index binary_integer;
v_source1 table_type;
begin
for j in 1..10 loop
if j = 1 then
v_source := 'AEA';
elsif j = 2 then
v_source := 'ACA';
elsif j = 3 then
v_source := 'AAA';
elsif j = 4 then
v_source := 'ABA';
elsif j = 5 then
v_source := 'ABA';
elsif j = 6 then
v_source := 'ADA';
elsif j = 7 then
v_source := 'ADA';
elsif j = 8 then
v_source := 'AEA';
elsif j = 9 then
v_source := 'AEA';
elsif j = 10 then
v_source := 'AAA';
end if ;
---- AAA 2
---- ABA 2
---- ACA 1
---- ADA 2
---- AEA 3
if v_source1.count > 0 Then
v_source_state := 'N';
for i in v_source1.first..v_source1.last loop
if v_source1(i).scode = v_source then
v_source1(i).scount := v_source1(i).scount + 1;
v_source_state := 'Y';
end if;
if i = v_source1.count and v_source_state = 'N' then
v_source1(i+1).scode := v_source;
v_source1(i+1).scount := 1;
end if;
end loop;
else
v_source1(1).scode := v_source;
v_source1(1).scount := 1;
end if;
end loop;
for k in v_source1.first..v_source1.last loop
dbms_output.put_line('Source: '||v_source1(k).scode||' Count: '||v_source1(k).scount);
end loop ;
v_sort_table.DELETE;
v_index := v_source1.FIRST;
LOOP
EXIT WHEN v_index IS NULL;
v_sort_table.EXTEND;
v_sort_table(v_sort_table.LAST) := source_sort(v_source1(v_index).scode,
v_source1(v_index).scount);
v_index := v_source1.NEXT(v_index);
END LOOP;
-- Sort the table in order of scode ascending
SELECT CAST (MULTISET (SELECT source_sort(scode, scount)
FROM TABLE(v_sort_table)
ORDER BY scode)
AS source_sort_table)
INTO v_sort_table
FROM dual;

Similar Messages

  • Sort collection  y multiple columns ........

    Hi,
      I have requirement to sort collection by two component . i know we can use collection_wrapper class sort method. but its sorting on one field  only .
    we need same functionality which we have in abap like sort <itab> by field1 field2 .  is there any way we can do it IC web client .
    Thanks,
    jack

    Hi Jack,
    Sorry I dont have sample code..but this is pretty simple.
    lr_iterator TYPE REF TO if_bol_bo_col_iterator.
             lr_entity   TYPE REF TO cl_crm_bol_entity,
             lr_node    TYPE REF TO if_bol_bo_property_access,
             lr_iterator = me->typed_context->context node->collection_wrapper->get_iterator( ).
        Loop at the iterator and build ur internal table
    IF lr_iterator IS BOUND.
          lr_entity ?= lr_iterator->get_first(  ).
          WHILE lr_entity IS BOUND.
              lr_entity->get_property_as_value( EXPORTING iv_attr_name = 'Column 1 '
                                                 IMPORTING ev_result    = lw_table-column1  ).
              lr_trade->get_property_as_value( EXPORTING iv_attr_name = 'Column 2'
                                                 IMPORTING ev_result    = lw_table-column2 ).
              APPEND lw_table TO lt_table.
            ENDIF.
    *       Get the Next Entity from the Iterator
            lr_entity ?= lr_iterator->get_next( ).
          ENDWHILE.
    Sort lt_table by column1 and column2.
           data: lr_new_coll TYPE REF TO cl_bsp_wd_collection_wrapper.
           CREATE OBJECT lr_new_coll.
            LOOP AT  lt_table INTO lw_table.
              CALL METHOD lr_iterator->find_by_property
                EXPORTING
                  iv_attr_name = 'column 1'
                  iv_value     = lw_table-column1
                RECEIVING
                  rv_result    = lr_node
              lr_new_coll->insert( EXPORTING iv_bo = r_node
                                             iv_index = sy-tabix ).
            ENDLOOP.
         CALL METHOD me->typed_context->context node ->set_collection
                EXPORTING
                  collection                    = lr_new_coll
                  iv_do_not_clear_previous_coll = abap_false
                  iv_try_to_keep_focus          = abap_true.
    I believe this is sufficient,if any issues come up do a where used on the methods I mentioned,
    you can get code snippets or else let me know please.
    Regards,
    Masood Imrani S.

  • Sorting Collections

    Is there a way to sort collections into date order?
    I am a recent newbie transferring from Aperture and I structure my files in the following way.
    Each Collection is Named By Year, Location and Date of shoot.
    But I notice that LR5 sorts them alphabetically. Am I missing something here.

    This sorts photos within a collection/folder, and does not sort the list of collections in Lightroom.
    To dsirjuesingh, what you are missing is that Lightroom offers other (much more flexible and powerful) ways to achieve this organization, rather than forcing all of this information into a collection name. For example, the location could be a keyword, and the date of shoot is embedded in EXIF metadata from your camera, so you don't really need to specify it in the collection name. Then in Lightroom, turn on the filter bar, and filter for photos with a desired keyword, and that were taken on a given day.

  • Sort collection by adding date

    Hi
    How can I sort the images inside a collection by the date of adding it to the collection?

    There is no automatic method but you can use collections for custom sorting i.e. you can drag images into your own order and they remain fixed regardless of where they are in your folders.
    Or you can drag in the filmstrip in any output module such a print, web etc.
    Take a look at this video for further information. It’s a bit slow starting so be patient.
    http://tv.adobe.com/watch/the-complete-picture-with-julieanne-kost/custom-sort-orders/

  • Sorting Collection Sets by Date

    Searched around for this first and now I'm asking the experts:
    I recently started using LR and have followed some workflow recommendations by Scott Kelby to set up my images in collection sets with collections within each set as follows:
    Collection Set Name
      - Full Shoot (collection)
      - Picks (collection)
      - Selects (collection)
    I want each collection set to be ordered by date (e.g. date of most recent image in set or date of import into LR).  The only 2 ways I've found to sort these are by Name or Kind.
    Any way to sort by date?
    I suppose I can rename each collection set so that it starts with the date, but that seems silly when the photos all have dates already assigned automatically.
    Thanks all.

    Well what I was looking for was to order the collection sets as opposed to the collections within them.  But based on your response, it looks like I do need to use a numerical prefix to do this.  (Thanks for the link to your workflow recommendations, I will spend more time checking them out.)
    So for example if my collections are currently sorted by name like this:
    Bangkok - Thailand
    - Full Shoot
    - Picks
    - Selects
    Hoi An - Vietnam
    - Full Shoot
    - Picks
    - Selects
    I'll add a date prefix so that the set is sorted like this:
    2009 1012  Hoi An - Vietnam
    - Full Shoot
    - Picks
    - Selects
    2009 1203 Bangkok - Thailand
    - Full Shoot
    - Picks
    - Selects
    This will sort the collections by date, but must check if it is possible to reverse the sort so that most recent shows first.
    dj paige:  Yes, I was looking to order the collection names, not the individual photos.
    Collections can be sorted by clicking on the + icon in the Collections panel and choosing either Sort by Name or
    Sort by Kind.  The only elaboration Adobe provides for Sort by Kind is to also call it "Sort by Type".
    Regards.

  • How to sort collections with EJB 2.0?

    As you know there is no ORDER BY statement in EJB QL; so I receive unsorted collection of objects from finder-methods. The process of Collections.sort() is very slow... Any ideas how to make a quick sort?

    Order by is a EJBQL 2.1 feature. It can be found in coming release of s1AS8.
    In JDK 1.4, merge sort is used in Collections.sort. It has a O(nlogn) algorithm. While quick sort only has an average O(nlogn) algorithm. If you are using custom Comparator, then you may to check about its implementation.

  • Problems Sorting Collections

    Hi,
    I wonder if there is any library that allows sorting a vector, in j2me?
    Cheers
    Bye

    Because, the interface Comparator doesn t exists in CLDC....
    That is why i m asking.
    Cheers(HELP)

  • Can someone explain simply what "collections.sort " does???

    Hi,
    i'm learning java with "teach yourself java 6 in 21 days" and i'm on day6 trying to implement interfaces and packages. what i can't understand is...
    there are two classes Storefront and Item in a package. there's another class GiftShop which imports this package. Item implements comparable(the interface) and defines the method comapreTo. Now GiftShop calls a method sort which is in Storefront which inturn calls Collection.sort passing it the linked list called catalog. as far as i understand, this collection.sort calls the compareTo method and sorts the linkedlist somehow. please explain to me how and please tell me where does this collection.sort comes in from? where does it reside basically????
    i'm confuseddddd and i really need to move on so please help help help
    package org.cadenhead.ecommerce;
    import java.util.*;
    public class Item implements Comparable {
         private String id;
         private String name;
         private double retail;
         private int quantity;
         private double price;
         Item(String idIn, String nameIn, String retailIn, String quanIn){
              id = idIn;
              name = nameIn;
              retail = Double.parseDouble(retailIn);
              quantity = Integer.parseInt(quanIn);
              if (quantity > 400)
                   price = retail * .5D;
              else if (quantity > 200)
                   price = retail * .6D;
              else
                   price = retail * .7D;
              price = Math.floor(price * 100 + .5) / 100;
         public int compareTo(Object obj) {
              Item temp = (Item)obj;
              if (this.price < temp.price)
                   return 1;
              else if (this.price > temp.price)
                   return -1;
              return 0;
         public String getId() {
              return id;
         public String getName() {
              return name;
         public double getRetail() {
              return retail;
         public double getPrice() {
              return price;
         public int getQuantity() {
              return quantity;
    package org.cadenhead.ecommerce;
    import java.util.*;
    public class Storefront {
         private LinkedList catalog = new LinkedList();
         public void addItem(String id, String name, String price, String quant) {
              Item it = new Item(id, name, price, quant);
              catalog.add(it);
         public Item getItem(int i) {
              return (Item)catalog.get(i);
         public int getSize() {
              return catalog.size();
         public void sort() {
              Collections.sort(catalog);
    import org.cadenhead.ecommerce.*;
    //import org.cadenhead.ecommerce.Item;
    public class GiftShop {
         public static void main(String[] arguments){
              //Item ti = new Item("C01", "MUG", "9.99", "150");
              Storefront store = new Storefront();
              store.addItem("C01", "MUG", "9.99", "150");
              store.addItem("C02", "LG MUG", "12.99", "82");
              store.addItem("C03", "MOUSEPAD", "10.49", "800");
              store.addItem("D01", "T SHIRT", "16.99", "90");
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                        "\n Name: " + show.getName());
              store.sort();
              System.out.println("Catalog Size: " + store.getSize());
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                        "\n Name: " + show.getName() +
                        "\n Retail Price: " + show.getRetail() +
                        "\n Price: " + show.getPrice() +
                        "\n Quantity: " + show.getQuantity());
    }

    Chiya wrote:
    what are code tags?When you post code, please post it between [code] and [/code] tags (you can also use the appropriate button on the message posting screen). It makes your code much easier to read and prevents accidental markup from the forum software.
    Example:import org.cadenhead.ecommerce.*;
    public class GiftShop {
         public static void main(String[] arguments){
              Storefront store = new Storefront();
              store.addItem("C01", "MUG", "9.99", "150");
              store.addItem("C02", "LG MUG", "12.99", "82");
              store.addItem("C03", "MOUSEPAD", "10.49", "800");
              store.addItem("D01", "T SHIRT", "16.99", "90");
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                   "\n Name: " + show.getName());
              store.sort();
              System.out.println("Catalog Size: " + store.getSize());
              for (int i = 0; i < store.getSize(); i++) {
                   Item show = (Item)store.getItem(i);
                   System.out.println("\n Item ID: " + show.getId() +
                   "\n Name: " + show.getName() +
                   "\n Retail Price: " + show.getRetail() +
                   "\n Price: " + show.getPrice() +
                   "\n Quantity: " + show.getQuantity());
    } ~

  • Collection sort of relation CMP field

    can I sort collection of relation CMP field declarativly?
    in orion-ejb-jar.xml?
    now I can do it either in SessionBean code or by creation of one more method findByFK1 - additional work -((

    I have one cmp ejb call 'R' with primary key id.
    Another cmp ejb call 'RS' with primary key id as well. This RS suppose to represent status of the R record which one R record may have multiple status.
    I added one cmp field from toplink workbench call 'status' under R and another cmp field call 'req' under RS. I did a one to many mapping on 'status' with reference descriptor RS bean. Then, I added another one to one mapping on 'req' with reference descriptor R bean.
    I got the new ejb-jar.xml after saving the project with the new relationships. However I get the error (as described in previous posting) from ejbc.
    My two attempts:
    1) If I remove that 1:1 relationship, ejbc is ok but data cannot be retrieve properly.
    2) I tried to remove the
    <cmp-field>
    <field-name>req</field-name>
    </cmp-field>
    manually from the ejb-jar.xml under 'RS' bean, ejbc is ok as well but again, data cannot be retrieved.
    I looked at the demos provided by toplink 4.0 installation, apparently they were able to add a mapping without using 'add cmp field' (this function automaticaly generates the <cmp-field> tags..)
    Thanks,
    Ivy

  • How to sort a object vector by its integer item ?

    hi everybody,
    [there were few topics on this in the forum, but nothing could solve my problem yet. so, please instruct me]
    I have to sort a vector which contains objects, where each object represents, different data types of values,
    ex: {obj1, obj2, obj3, ....}
    obj1---->{String name, int ID, String[] departments}
    i have to sort this vector at three times, once by name, then by ID and then by departments.
    Leaving name and department , first i want to sort the ID of each object and then re-arrange the order of objects in the array according to new order.
    what i did was, copied the vector all objects' ID values to an integer array then i sorted it using selection sort. but now i want to re-arrange the vector, but i still can't. please guide.
    here is the sort i did, and the
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i < ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    I do understand this is some sort of database sort type of a question. but there's no database. it's simply i just want to sort the vector.
    Thank you.

    hi camickr,
    thank you for the detailed reply. but i still don't understand somethings. i tried to read the API and look for the collections.
    i have ObjectStore_initialData class (similar to person class), so do i still have to do a comparable class out of this class ? please simplify that.
    public class ObjectStore_initialData
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    /*next class is the interface to collect the values from the user and put all of them at once in a vector*/
    //this class is to sort the vector by ID
    public class sorter
       public sorter()
       public static void sortbyID(Vector mintomaxID)
             int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    //*****here is where i need to re-arrange the entire vector by ID.
    /*new comparable class */
    public class ObjectStore_initialData implements Comparable
         String NAME;
         int ID;
         String[] DPART;     
         public ObjectStore_initialData(String name, int id, String[] departments)
              NAME=name;
              ID=id;
              DPART = departments;
    public String getName()//----
              return NAME;
    public String getID()//----
              return ID;
    public String getDpart()//----
              return DPART;
    static class IDComparator implements Comparator
              public int compare(Object o1, Object o2)
                   ObjectStore_initialData p1 = (ObjectStore_initialData )o1;
                   ObjectStore_initialData p2 = (ObjectStore_initialData )o2;
                   return p1.getID() - p2.getID();
    /*how can i put the vector here to sort? */
    public sorter()
    public static void sortbyID(Vector mintomaxID)
    int[] ID = new int[mintomaxID.size()];
              for(int i=0;i<mintomaxID.size();i++)
                   ObjectStore_initialData obj_id = (ObjectStore_initialData)mintomaxID.elementAt(i);
                   ID[i] = obj_id.getID();
              System.out.println("Before sorting array");
              for(int i=0;i<ID.length;i++)
                   System.out.println(ID[i]);     
              System.out.println();
              int i, j, m, mi;
    for (i = 0; i >< ID.length - 1; i++) {
    /* find the minimum */
    mi = i;
    for (j = i+1; j < ID.length; j++) {
    if (ID[j] < ID[mi]) {
    mi = j;
    m = ID[mi];
    /* move elements to the right */
    for (j = mi; j > i; j--) {
    ID[j] = ID[j-1];
    ID[i] = m;
    System.out.println("After sorting array");
    for(int y=0;y<ID.length;y++)
                   System.out.println(ID[y]);     
    /* using collections to sort*/
    Collections.sort(mintomaxID, new IDComparator());
    and to check the new order i wanted to print the vector to command line.
    still it doesn't do anything.
    the url you mentioned is good as i see. but how can i implement that in my class ? please instruct and simplify. i know i just repeated the code, i didn't understand to do a comparable class in collections for this class. Please explain where i'm head to and where's my misleading point here.
    Thank you.
    Message was edited by:
    ArchiEnger.711

  • JSP TableView Sorting Problem

    I have been trying to get a tableview to be sortable by clicking on the header of columns.  I have been reviewing existing threads on the forum in particular the one below.
    https://forums.sdn.sap.com/thread.jspa?threadID=16417
    I seem to understand the concept but for some reason my table does not sort, it just does nothing.  Could someone take a look and see if you can find any problems - I can't wait to give points.
    Here is all my code.
    Here is the Java....
    package MSSPackage;
    import MSSBeanPackage.PositionOverviewBean;
    import MSSPackage.SortTableModel;
    import com.sapportals.htmlb.page.DynPage;
    import com.sapportals.htmlb.page.PageException;
    import com.sapportals.portal.htmlb.page.JSPDynPage;
    import com.sapportals.portal.htmlb.page.PageProcessorComponent;
    import com.sapportals.portal.prt.component.IPortalComponentContext;
    import com.sapportals.portal.prt.component.IPortalComponentProfile;
    import com.sapportals.portal.prt.component.IPortalComponentRequest;
    import com.sapportals.portal.prt.component.IPortalComponentSession;
    import com.sapportals.htmlb.event.*;
    import com.sapportals.htmlb.*;
    import com.sapportals.htmlb.table.*;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    import javax.servlet.http.*;
    // SAP RFC Imports
    import com.sap.mw.jco.IFunctionTemplate;
    import com.sap.mw.jco.JCO;
    import com.sapportals.portal.prt.service.jco.IJCOClientPoolEntry;
    import com.sapportals.portal.prt.service.jco.IJCOClientService;
    import com.sapportals.portal.prt.runtime.PortalRuntime;
    import java.util.*;
    public class PositionOverview extends PageProcessorComponent {
      public DynPage getPage(){
         return new PositionOverviewDynPage();
      public static class PositionOverviewDynPage extends JSPDynPage{
         JCO.Repository mRepository;
         public JCO.Table tblRelations;
         public JCO.Table tblPositions;     
         public SortTableModel tableModel;
         public int visibleRow = 1;     
         private boolean OrgUnitSelected = false;
         public void doInitialization(){
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean oBean = new PositionOverviewBean();
              // Table Start row
              oBean.setvisibleRow(new Integer(this.visibleRow).toString());          
              oSession.putValue("myBean", oBean);
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
              IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              // Define bean reference to bean
              PositionOverviewBean myBean = new PositionOverviewBean();
              // Table Start row
              myBean.setvisibleRow(new Integer(this.visibleRow).toString());
              // Place bean in user profile.          
              myProfile.putValue("myBean", myBean);
         public void doProcessAfterInput() throws PageException {
         public void doProcessBeforeOutput() throws PageException {
              String NavType = "RCORGUNIT";
              String OType = "O";
              //String OBjid = "10004399";
              String OBjid = "";
              String sapSystem = "SAP_R3_HumanResources";          
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean myBean = (PositionOverviewBean) oSession.getValue("myBean");
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
    /*          IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              //HttpSession session = request.getServletRequest().getSession();          //dmm
              //Get Bean from Profile
              PositionOverviewBean myBean = (PositionOverviewBean) myProfile.getValue("myBean");
              //PositionOverviewBean myDataBean = (PositionOverviewBean) session.getValue("POviewBean");               //dmm
              String ddlbSelection = "";
              String ddlbValue = "";
              DropdownListBox ddlbOrgUnits = (DropdownListBox) getComponentByName("ddlbOrgUnits");
              if (ddlbOrgUnits != null)
                   ddlbSelection = ddlbOrgUnits.getSelection();
                   ddlbValue = ddlbOrgUnits.getValueAsDataType().getValueAsString();
                   OBjid = ddlbValue;
                   myBean.setObjId(OBjid);
              else
                   OBjid = "";
                   myBean.setObjId(OBjid);                 
              IJCOClientService clientService;
              IJCOClientPoolEntry poolEntry;          
              JCO.Client client;          
              try
                   clientService = (IJCOClientService) PortalRuntime.getRuntimeResources().getService(IJCOClientService.KEY);
                   poolEntry = clientService.getJCOClientPoolEntry(sapSystem, request);
                   client = poolEntry.getJCOClient();
                // connect to SAP system, logon
                   client.connect();
                // Create Jco Repository Object
                   mRepository = new JCO.Repository("R3USERMENU", client);
                // Reset function object
                   JCO.Function function = null;
                // Run RFC Module on SAP system
                   function = this.createFunction("HRWPC_GET_NAV_OBJECTS");
                   JCO.ParameterList input = function.getImportParameterList();
                   input.setValue("RCORGUNIT", "NAVTYPE");               
                   client.execute(function);
                   tblRelations = function.getTableParameterList().getTable("RESULT_OBJEC");
                   myBean.setRowcnt(tblRelations.getNumRows());
                   if (tblRelations.getNumRows() != 0)               
                        myBean.setOrgUnits(tblRelations);
                        if (ddlbOrgUnits == null)
                             // check to see if there is not a position id already assigned
                             tblRelations.setRow(0);
                             OBjid = tblRelations.getString("OBJID");
                             myBean.setObjId(OBjid);
                             //myBean.sTemp = OBjid;                         
                   // GET THE POSITION DETAILS
                   function = null;
                   input = null;
                   function = this.createFunction("Z_GET_POSITION_OVERVIEW");
                   input = function.getImportParameterList();               
                   input.setValue(NavType, "NAVTYPE");               
                   input.setValue(OType, "OTYPE");
                   input.setValue(OBjid, "OBJID");               
                   client.execute(function);
                   tblPositions = function.getTableParameterList().getTable("RESULT_OBJEC");
                   myBean.setRowcnt(tblPositions.getNumRows());
                   tableViewFormat();
                   tableModel.setTesting("Startxxxx");
                   myBean.settableModel(tableModel);
                   //tableModel.setTesting("SSSS");               
                   //myDataBean.settableModel(tableModel);                                             //dmm               
                   //session.setAttribute("POviewBean", myDataBean);                                //dmm
                   oSession.putValue("myBean", myBean);
              //Release pool entry
              poolEntry.release();                           
           catch(Exception ex)
                //name = ex.getMessage();                         
           //String sTest = "this is a test";      
           //request.getComponentSession().putValue("Test", sTest);
           //myProfile.putValue("Testx", sTest);
           this.setJspName("PositionOverviewJSP.jsp");
         public void getPositions()
              String NavType;
              String Root_Ot;
              String Root_ObjId;
         public void tableViewFormat()
              // Define the vectors used to build tableView
              Vector tempRec = new Vector();
              Vector dataRec = new Vector();
              String sDate = "";
              String sPosLink = "";
              String sPosVal = "";
              String sENameLink = "";
              String sENameVal = "";
              String sStatus = "";
              // Loop at company code list and add to vectors
              for (int i = 0; i < tblPositions.getNumRows(); i++)
                   tblPositions.setRow(i);
                   tempRec = new Vector();
                   sStatus = (String) tblPositions.getString("STATUS");
                   if (sStatus != null)
                        if (sStatus.equals("0"))                    
                             sDate = tblPositions.getString("ZHR_VACANT_BEGDA");
                             sDate = sDate.substring(5, 7) + "/" + sDate.substring(8, 10) + "/" +  sDate.substring(0, 4);                         
                        else
                             sDate = "";                    
                   sPosVal = tblPositions.getString("STEXT");
                   sENameVal = tblPositions.getString("ENAME");
                   if (sPosVal.equals(""))
                        sPosLink = sPosVal;
                   else
                        sPosLink = "<a HREF="myLink" onclick="return EPCM.doNavigate('ROLES://portal_content/com.sap.portal.migrated/ep_5.0/pages/com.sap.pct.hcm.positionprofile?CKey=000000" + tblPositions.getString("OBJID") + "', 1)">" + tblPositions.getString("STEXT") + "</a>";
                   if (sENameVal.equals(""))
                        sENameLink = sENameVal;
                   else
                        sENameLink = "<a HREF="myLink" onclick="return EPCM.doNavigate('ROLES://portal_content/com.phi/com.phi.mgt/com.phi.mss/com.phi.hr/com.phi.pages/com.phi.mgt.mss.hr.pages.positionholder?CKey=000000" + tblPositions.getString("OBJID") + "', 1)">" + tblPositions.getString("ENAME") + "</a>";
                   tempRec.addElement(sStatus);
                   tempRec.addElement(tblPositions.getString("OBJID"));
                   tempRec.addElement(sPosLink);
                   tempRec.addElement(sENameLink);
                   tempRec.addElement(sDate);               
                   dataRec.addElement(tempRec);
              // Then define the technical column names
              Vector colNames = new Vector();
              colNames.addElement("STATUS");
              colNames.addElement("OBJID");
              colNames.addElement("STEXT");     
              colNames.addElement("ENAME");
              colNames.addElement("ZHR_VACANT_BEGDA");
              // Now we build the actual tableView
              //tableModel = new DefaultTableViewModel(dataRec, colNames);
              tableModel = new SortTableModel(dataRec, colNames, 5);     
              // Define tableView parameters
              tableModel.setKeyColumn(2);
              TableColumn column = tableModel.getColumn("STATUS");
              column.setEncode(false);
              column.setType(com.sapportals.htmlb.enum.TableColumnType.USER);
              column.setTitle("Vacant");
              column = tableModel.getColumn("OBJID");
              column.setTitle("Position Number");
              column = tableModel.getColumn("STEXT");
              column.setTitle("Position");
              column = tableModel.getColumn("ENAME");
              column.setTitle("Holder of Position");          
              column = tableModel.getColumn("ZHR_VACANT_BEGDA");
              column.setTitle("Vacant as of");
         //     * Navigation Button Clicked
         public void myOnNavigate(Event event)
              TableNavigationEvent tne = (TableNavigationEvent) event;
              visibleRow = tne.getFirstVisibleRowAfter();
              // Define request, context and profile containers         
              IPortalComponentRequest request = (IPortalComponentRequest) this.getRequest();
              IPortalComponentContext myContext = request.getComponentContext();
              IPortalComponentProfile myProfile = myContext.getProfile();
              // Get Bean from profile
              PositionOverviewBean myBean = (PositionOverviewBean) myProfile.getValue("myBean");
              // Table Start row
              myBean.setvisibleRow(new Integer(this.visibleRow).toString());
         public void onHeaderClick(Event event)
              IPortalComponentSession oSession = ((IPortalComponentRequest)getRequest()).getComponentSession();
              PositionOverviewBean myBean = (PositionOverviewBean) oSession.getValue("myBean");
              TableHeaderClickEvent tne = (TableHeaderClickEvent) event; // get the event
              SortTableModel tblModel = myBean.gettableModel();
              //tblModel.sort();
              int col = 3;
              tblModel.sortByColumn(col);
              myBean.settableModel(tblModel);
              oSession.putValue("myBean", myBean);
         // Create Function object for RFC Calls
         public JCO.Function createFunction(String name) throws Exception
              try
                   IFunctionTemplate ft = mRepository.getFunctionTemplate(name.toUpperCase());
                   if (ft == null)
                        return null;
                   return ft.getFunction();
              catch (Exception ex)
                   ex.printStackTrace();
                   throw new Exception("Problem retrieving JCO.Function object");
         public void onSelectddlbOrgUnits(Event event) throws PageException
              OrgUnitSelected = true;          
    Here is the JSP
    <%@ page import="com.sap.mw.jco.*" %>
    <%@ page import="com.sapportals.htmlb.enum.*" %>
    <%@ page import="MSSPackage.TableViewCellRenderer" %>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentRequest" %>
    <%@ page import="javax.servlet.http.*" %>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentContext" %>
    <%@ taglib uri="tagLib" prefix="hbj" %>
    <hbj:content id="myContext" >
         <hbj:page title="PageTitle">
              <hbj:form id="myFormId" >  
              <jsp:useBean id="myBean" scope="session" class="MSSBeanPackage.PositionOverviewBean" />     
                   <hbj:gridLayout rowSize="1" columnSize="1" cellSpacing="1">
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="1">
                             <hbj:textView id="ddlbLable" text="Select organizational unit to display positions" design="STANDARD" />
                        </hbj:gridLayoutCell>                         
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="2">
                             <hbj:dropdownListBox id="ddlbOrgUnits" onSelect="onSelectddlbOrgUnits" selection="<%=myBean.getObjId()%>">                                                       
                                  <%                         
                                       JCO.Table org_units = null;                                                       
                                       org_units = myBean.getOrgUnits();
                                       for (int i = 0; i < org_units.getNumRows(); i++)
                                            org_units.setRow(i);
                                            String sUnit = org_units.getString("STEXT");
                                            String Unit_Id = org_units.getString("OBJID");
                                  %>
                                  <hbj:listBoxItem key="<%=Unit_Id%>" value="<%=sUnit%>" />
                                  <%
                                  %>
                             </hbj:dropdownListBox>                                                                                                   
                        </hbj:gridLayoutCell>
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="3">
                             <hbj:textView id="listLable" text="To designate a vacant position, click the icon in the 'Create Form' column" design="STANDARD" />                    
                        </hbj:gridLayoutCell>                    
                        <hbj:gridLayoutCell columnIndex="1" rowIndex="4">     
                             <hbj:tableView
                                  id="myTableView"
                                  headerVisible="true"
                                  footerVisible="true"
                                  fillUpEmptyRows="true"
                                  selectionMode="NONE"                              
                                  navigationMode="BYPAGE"
                                  onNavigate="myOnNavigate"                                        
                                  visibleFirstRow="<%= myBean.getvisibleRow() %>"                                                  
                                  visibleRowCount="5" >                                                            
                                  <%
                                  myTableView.setOnHeaderClick("onHeaderClick");
                                  myTableView.setUserTypeCellRenderer(new TableViewCellRenderer());                                                             
                                  myTableView.setModel(myBean.gettableModel());
                                  myTableView.setColumnType(TableColumnType.LINK, 3);
                                  myTableView.setColumnType(TableColumnType.LINK, 4);                              
                                  %>
                             </hbj:tableView>
                        </hbj:gridLayoutCell>                                        
                   </hbj:gridLayout>   
              </hbj:form>
         </hbj:page>
    </hbj:content>
    Here is the BEAN
    package MSSBeanPackage;
    //import com.sapportals.htmlb.enum.TableColumnType;
    import MSSPackage.SortTableModel;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    //import com.sapportals.htmlb.table.TableColumn;
    //import com.sapportals.htmlb.table.TableView;
    //import com.sapportals.htmlb.table.TableViewModel;
    import com.sap.mw.jco.JCO;
    import com.sap.mw.jco.JCO.Table;
    public class PositionOverviewBean {
    //     public DefaultTableViewModel tableModel;
         public SortTableModel tableModel;
         public JCO.Table OrgUnits;
         public String ObjId;
         public String visibleRow;
         public int rowcnt;
         public String sTemp;
         // Get and Set methods for table model
    //     public DefaultTableViewModel gettableModel() { return tableModel; }
    //     public void settableModel(DefaultTableViewModel tableModel)     { this.tableModel = tableModel;     }
         public SortTableModel gettableModel() { return tableModel; }
         public void settableModel(SortTableModel IntableModel)     { this.tableModel = IntableModel;     }     
         public JCO.Table getOrgUnits()     { return OrgUnits; }
         public void setOrgUnits(JCO.Table value) { this.OrgUnits = value; }
         // Get and Set methods for visiblerow
         public String getvisibleRow() {     return visibleRow; }
         public void setvisibleRow(String visibleRow) { this.visibleRow = visibleRow; }     
         public int getRowcnt() { return this.rowcnt; }
         public void setRowcnt(int rowcnt) { this.rowcnt = rowcnt; }
         public String getObjId() { return this.ObjId; }
         public void setObjId(String value) { this.ObjId = value; }     
    Here is the sorting class
    package MSSPackage;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.Vector;
    import com.sapportals.htmlb.table.DefaultTableViewModel;
    public class SortTableModel extends DefaultTableViewModel implements Comparator {
         //protected int currCol;
         public int currCol;
         protected Vector ascendCol; // this vector stores the state (ascending or descending) of each column
         protected Integer one = new Integer(1);
         protected Integer minusOne = new Integer(-1);
         public String testing;
         public SortTableModel()
              super();
              ascendCol = new Vector();
         public SortTableModel(Vector vec)
              super(vec);
              ascendCol = new Vector();
         public SortTableModel(Vector vec, Vector vec2, int numberOfColumns)
              super(vec, vec2);
              ascendCol = new Vector();
              setSortOrder(numberOfColumns);
         public int compare (Object v1, Object v2)
              // the comparison is between 2 vectors, each representing a row
              // the comparison is done between 2 objects from the different rows that are in the column that is being sorted
              int ascending = ((Integer)ascendCol.get(currCol)).intValue();
              if (v1 == null && v2 == null)
                   return 0;
              else if (v2 == null)
              { // Define null less than everything.
                   return 1 * ascending;
              else if (v1 == null)
                   return -1 * ascending;
              Object o1 = ((Vector)v1).get(currCol);
              Object o2 = ((Vector)v2).get(currCol);
              // If both values are null, return 0.
              if (o1 == null && o2 == null)
                   return 0;
              else if (o2 == null)
              { // Define null less than everything.
                   return 1 * ascending;
              else if (o1 == null)
                   return -1 * ascending;
              if (o1 instanceof Number && o2 instanceof Number)
                   Number n1 = (Number)o1;
                   double d1 = n1.doubleValue();
                   Number n2 = (Number)o2;
                   double d2 = n2.doubleValue();
                   if (d1 == d2)
                        return 0;
                   else if (d1 > d2)
                        return 1 * ascending;
                   else {
                        return -1 * ascending;
              else if (o1 instanceof Boolean && o2 instanceof Boolean)
                   Boolean bool1 = (Boolean)o1;
                   boolean b1 = bool1.booleanValue();
                   Boolean bool2 = (Boolean)o2;
                   boolean b2 = bool2.booleanValue();
                   if (b1 == b2)
                        return 0;
                   else if (b1)
                        return 1 * ascending;
                   else
                        return -1 * ascending;
              else
                   // default case
                   if (o1 instanceof Comparable && o2 instanceof Comparable)
                        Comparable c1 = (Comparable)o1;
                        Comparable c2 = (Comparable)o2; // superflous cast, no need for it!
                        try
                             return c1.compareTo(c2) * ascending;
                        catch (ClassCastException cce)
                        // forget it... we'll deal with them like 2 normal objects below.
                   String s1 = o1.toString();
                   String s2 = o2.toString();
                   return s1.compareTo(s2) * ascending;
         * This method sorts the rows using Java's Collections class.
         * After sorting, it changes the state of the column -
         * if the column was ascending, its new state is descending, and vice versa.
         public void sort()
              Collections.sort(dataVector, this);          
              //Collections.sort(dataVector);
              Integer val = (Integer)ascendCol.get(currCol);
              ascendCol.remove(currCol);
              if (val.equals(one)) // change the state of the column
                   ascendCol.add(currCol, minusOne);
              else
                   ascendCol.add(currCol, one);
         public void sortByColumn(int column)
              this.currCol = column;
              sort();
         public void setSortOrder(int numberOfColumns)
              for (int i = 0; i < numberOfColumns; i++)
                   ascendCol.add(one);
         public void setTesting(String inStr)
              testing = inStr;
    Any help would be greatly apprciated and rewarded...

    Hi Don,
    be aware that after the method onHeaderClick(Event event) is executed the method doProcessBeforeOutput() is executed as well.
    I look over your code and found the following:
    1) In method onHeaderClick you sort the table model and store the table model in the bean
    2) In method doProcessBeforeOutput() you create a new table model from scratch (in helper method tableViewFormat())and store it in the bean. Thus you overwrite the sorted model.
    I suggest that you move the initial creation of the table model in method doInitialization(). Do not forget to store the created table in the bean. In method doProcessBeforeOutput() you retrieve the table model from the bean instead of creating a new one for every request.
    Best regards,
    Martin

  • Is it possible to create exception rule in Comparator sort order?

    I have been working on trying to learn how to use Comparators to sort Collections... In one of my recent experiments, I tried to order a PriorityQueue of String elements alphabetically, in ascending order, with one exception: any word beginning with the letter "z" should be given a higher priority than any other word. I haven't been able to find a way to do this, nor to discern whether or not it's possible.
    Any help is appreciated.

    Try something like this:public class MyComparator implements Comparator<String> {
        @Override
        public int compare(String s1, String s2) {
            boolean s1StartsWithZ = s1.startsWith("z");
            boolean s2StartsWithZ = s2.startsWith("z");
            if (s1StartsWithZ && !s2StartsWithZ) return 1;
            if (s2StartsWithZ && !s1StartsWithZ) return -1;
            return s1.compareTo(s2);
    }

  • Sort a vector of objects by one of its attributes

    Hi all!
    I have created this class:
    public class Client {
    private int numero;
    private double tempsEntrada;
    private double tempsServei;
    private double tempsIniciSessio;
    private char tipus;
    * Creates a new instance of Client
    public Client(int num, double temp,double servei, char tip) {
    numero = num;
    arrivalTime = temp;
    serviceTime = servei;
    tipus = tip;
    public char getTipus()
    return tipus;
    public int getNumero()
    return numero;
    public double getTempsEntrada()
    return arrivalTime;
    public double getTempsServei()
    return serviceTime;
    Now I've done a java vector of this object, and I want to sort it by arrivalTime.
    The class comparer looks like this
    public class Comparer implements Comparator {
    public int compare(Object obj1, Object obj2)
    double temps1 = ((Client)obj1).getTempsEntrada();
    double temps2 = ((Client)obj2).getTempsEntrada();
    return (int)(temps1 - temps2);
    now when I do Collections.sort(vector);
    this is the error reported:
    Exception in thread "main" java.lang.ClassCastException: cafevirtual.Client cannot be cast to java.lang.Comparable
    at java.util.Arrays.mergeSort(Arrays.java:1144)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.mergeSort(Arrays.java:1155)
    at java.util.Arrays.sort(Arrays.java:1079)
    at java.util.Collections.sort(Collections.java:117)
    at cafevirtual.Main.main(Main.java:76)
    Java Result: 1
    what's wrong?
    thanks!

    Your Client class does not implement Comparable. You have to specify the Comparator to use: Collections.sort(vector, new Comparer());

  • Sorting a vector of objects using attribute of object class as comparator

    i would like to sort a vector of objects using an attribute of object class as comparator. let me explain, i'm not sure to be clear.
    class MyObject{
    String name;
    int value1;
    int value2;
    int value3;
    i've got a Vector made of MyObject objects, and i would sort it, for instance, into ascending numerical order of the value1 attribute. Could someone help me please?
    KINSKI.

    Vector does not implement a sorted collection, so you can't use a Comparator. Why don't you use a TreeSet? Then you couldclass MyObject
      String name;
      int value1;
      int value2;
      int value3;
      // Override equals() in this class to match what our comparator does
      boolean equals (Object cand)
        // Verify comparability; this will also allow subclasses.
        if (cand !instanceof MyObject)
          throw new ClassCastException();
        return value1 = cand.value1;
      // Provide the comparator for this class. Make it static; instance not required
      static Comparator getComparator ()
        // Return this class's comparator
        return new MyClassComparator();
      // Define a comparator for this class
      private static class MyClassComparator implements Comparator
        compare (Object cand1, Object cand2)
          // Verify comparability; this will also allow subclasses.
          if ((cand1 !instanceof MyObject) || (cand2 !instanceof MyObject))
            throw new ClassCastException();
          // Compare. Less-than return -1
          if ((MyObject) cand1.value1 < (MyObject) cand2.value1))
            return -1;
          // Greater-than return 1
          else if ((MyObject) cand1.value1 > (MyObject) cand2.value1))
            return 1;
          // Equal-to return 0.
          else
            return 0;
    }then just pass MyObject.getComparator() (you don't need to create an instance) when you create the TreeSet.

  • Comparable linked list sorting

    i have been trying to find a way to sort a link listed. After some reading i found out that it is probably best to use collections.sort(list). I think i understand how to implement it , i need to declare a compareto and equals method. However, most of the reading i have done shows how to create a collection from a linked list and add items to the collection and sort them, however it doesn show how to copy this sorted collection back inot a linked list. I need to remove items and add items to the sorted linked list. Is it possible to create a linked list, sort it using the collection sort and return the sorted linked list? I have looked in the api's but got confused!!

    You don't need to copy anything.
    List list = new LinkedList(); // or ArrayList
    // list.add stuff
    Collections.sort(list); Assuming whatever you added to the list implements Comarable, the list is now sorted.

Maybe you are looking for