Monday, 13 April 2020

TableSaw: Sort elements of table in both ascending and descending order

Minus sign preceding the name of column, used to sort the column in descending order.

Example
Table sorted = table.sortOn("FirstName", "-LastName");

Above statement sort the elements by ‘FirstName’ in ascending order and ‘LastName’ in descending order.

App.java
package com.sample.app;

import tech.tablesaw.api.IntColumn;
import tech.tablesaw.api.StringColumn;
import tech.tablesaw.api.Table;

public class App {

  public static void main(String args[]) {
    int[] empIds = { 1, 2, 3, 4, 5, 6 };
    String[] firstNames = { "Hari", "Ram", "Sowmya", "Chamu", "Swethank", "Chamu" };
    String[] lastNames = { "Krishna", "Gurram", "Maj", "Maj", "Baji", "Gurram" };

    Table table = Table.create().addColumns(IntColumn.create("Employee Id", empIds))
        .addColumns(StringColumn.create("FirstName", firstNames))
        .addColumns(StringColumn.create("LastName", lastNames));

    Table sorted = table.sortOn("FirstName", "-LastName");
    
    System.out.println(table.print());
    System.out.println("\nAfter Sorting\n");
    System.out.println(sorted.print());
    
  }
}

Output

Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Maj  |
           5  |   Swethank  |      Baji  |
           6  |      Chamu  |    Gurram  |

After Sorting

 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           4  |      Chamu  |       Maj  |
           6  |      Chamu  |    Gurram  |
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           5  |   Swethank  |      Baji  |


Previous                                                    Next                                                    Home

No comments:

Post a Comment