Skip to content

DataSet

landawn edited this page May 1, 2018 · 6 revisions

DataSet supports distinct/merge/sort/groupBy/join/union/except/intersect/paginate/filter/count/toJOSN/toXML/... With the methods in N and lambda in Java 8, DataSet enlarges the ability to data analyze with simple/concise APIs. An instance of DataSet can be obtained by executing a SQL query (with JdbcUtil/SQLExecutor), or loading from CSV by CSVUtil, or parsing JSON by JSONParser, or from a map or a list of entity/map/array with the method asDataSet in class N.

public void test_DataSet() {
    Timestamp now = new Timestamp(System.currentTimeMillis());
    Object[] parameters1 = asArray("fn", "ln", UUID.randomUUID().toString(), now, now);
    Object[] parameters2 = asArray("fn", "ln", UUID.randomUUID().toString(), now, now);
    sqlExecutor.batchInsert(INSERT_ACCOUNT, new Object[] { parameters1, parameters2 });

    String sql = NE.select(Account.class, asSet(Account.DEVICES)).from(Account._).sql();
    DataSet dataSet = sqlExecutor.query(sql);
    dataSet.println();

    String json = dataSet.toJSON();
    println(json);

    String xml = dataSet.toXML();
    println(xml);

    String csv = dataSet.toCSV();
    println(csv);

    PaginatedDataSet paginatedResult = dataSet.paginate(25);
    println(paginatedResult.firstPage());

    // create account list from data set
    List<Account> accounts = dataSet.toList(Account.class);

    // convert account list to data set
    DataSet dataSet2 = asDataSet(dataSet.columnNameList(), accounts);    
    dataSet2.println();
    
    dataSet2.sortBy(asList("firstName", "lastName"));

    DataSet dataSet3 = dataSet2.groupBy("firstName");
    println(dataSet3);

    DataSet dataSet4 = dataSet2.filter("firstName", (String a) -> a.startsWith("ab"));
    println(dataSet4);

    int count = dataSet2.count("firstName", (String a) -> a.startsWith("ab"));
    println(count);

    DataSet dataSet5 = dataSet2.intersect(dataSet4);
    println(dataSet5);
}