Sunday, 12 April 2020

TableSaw: Add rows from other table

‘table.addRow’ method adds a row from source table to destination table.

Example
‘destinationTable.addRow(rowNumberToAdd, sourceTable)’

Below snippet add all the rows from destinationTable to sourceTable.
for(int i = 0; i < destinationTable.rowCount(); i++) {
         sourceTable.addRow(i, destinationTable);
}

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 };
  String[] firstNames = { "Hari", "Ram", "Sowmya", "Chamu", "Hareesh" };
  String[] lastNames = { "Krishna", "Gurram", "Maj", "Dev", "Baji" };

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

  int[] empIds1 = { 5, 6 };
  String[] firstNames1 = { "Sarala", "Vimala" };
  String[] lastNames1 = { "Maj", "Krishna" };

  Table destinationTable = Table.create().addColumns(IntColumn.create("Employee Id", empIds1))
    .addColumns(StringColumn.create("FirstName", firstNames1))
    .addColumns(StringColumn.create("LastName", lastNames1));

  System.out.println("Source Table : " + sourceTable.print() + "\n");
  System.out.println("Destination Table : \n" + destinationTable.print());
  
  System.out.println("\nAdding all the rows from destination table to source table\n");
  
  for(int i = 0; i < destinationTable.rowCount(); i++) {
   sourceTable.addRow(i, destinationTable);
  }
  
  System.out.println("Source Table : \n" + sourceTable.print() + "\n");
 }
}

Output

Source Table :  Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Dev  |
           5  |    Hareesh  |      Baji  |

Destination Table : 
 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           5  |     Sarala  |       Maj  |
           6  |     Vimala  |   Krishna  |

Adding all the rows from destination table to source table

Source Table : 
 Employee Id  |  FirstName  |  LastName  |
------------------------------------------
           1  |       Hari  |   Krishna  |
           2  |        Ram  |    Gurram  |
           3  |     Sowmya  |       Maj  |
           4  |      Chamu  |       Dev  |
           5  |    Hareesh  |      Baji  |
           5  |     Sarala  |       Maj  |
           6  |     Vimala  |   Krishna  |





Previous                                                    Next                                                    Home

No comments:

Post a Comment