Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Processing Internal Data →  Internal Tables →  System Class for Internal Tables →  Examples of Virtual Sorting of Internal Tables 

Virtual Sorting of an Internal Table with Filters

This example demonstrates the virtual sorting of an internal table with row filtering.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    TYPES
      itab TYPE STANDARD TABLE OF i WITH EMPTY KEY.

    DATA(rnd) = cl_abap_random_int=>create( seed = + sy-uzeit
                                           min  = 1
                                           max  = 10 ).

    DATA(itab) = VALUE itab( FOR i = 1 UNTIL i > 10
                             ( rnd->get_next( ) ) ).

    DATA(out) = cl_demo_output=>new( ).

    out->write( itab ).

    out->next_section( `Virtual Sort by table_line with Filter` ).

    DATA(v_index) =
      cl_abap_itab_utilities=>virtual_sort(
        im_virtual_source = VALUE #(
         ( source     = REF #( itab )
           components = VALUE #( ( name = 'table_line' ) ) ) )
        im_filter_index =  VALUE #( ( 1 ) ( 3 ) ( 5 ) ( 7 ) ( 9 ) ) ).

    out->write( v_index ).

    DATA sorted_tab TYPE itab.
    sorted_tab = VALUE #( FOR idx IN v_index ( itab[ idx ] ) ).

    out->write( sorted_tab ).

    out->display( ).

Description

An internal table filled with random numbers is sorted in ascending order by its row content using the method VIRTUAL_SORT of system class CL_ABAP_ITAB_UTILITIES. This passes a table filter_tab containing the row numbers to be sorted. The returned array contains exactly these row numbers in the sort order. A table sorted_tab is constructed in this order from the respective rows of itab.