Skip to content

Accessing Objects

Jan Wiemer edited this page Dec 27, 2020 · 9 revisions

Accessing Objects

The API of the JACIS store provides access to the stored objects using a Java 8 type stream API. First we create some example objects to have some data to play around:

    container.withLocalTx(() -> {
      store.update("account0", new Account("account0").withdraw(100));
      store.update("account1", new Account("account1").deposit(100));
      store.update("account2", new Account("account2").deposit(200));
      store.update("account3", new Account("account3").deposit(300));
      store.update("account4", new Account("account4").deposit(400));
      store.update("account5", new Account("account5").deposit(500));
      store.update("account6", new Account("account6").deposit(600));
      store.update("account7", new Account("account7").deposit(700));
      store.update("account8", new Account("account8").deposit(800));
      store.update("account9", new Account("account9").deposit(900));
    });

Now we show some examples how to use the stream API:

    // To cumulate values usually read only access is enough (this is possible without a transaction)
    System.out.println("sum=" + store.streamReadOnly().mapToLong(acc -> acc.getBalance()).sum());

    // streaming the objects starting with a filter
    System.out.println("#>500=" + store.streamReadOnly(acc -> acc.getBalance() > 500).count());

    // as an example to modify some objects add 10% interest to each account with a positive balance
    container.withLocalTx(() -> {
      store.stream(acc -> acc.getBalance() > 0).forEach(acc -> {
        store.update(acc.getName(), acc.deposit(acc.getBalance() / 10));
      });
    });

    // finally output all accounts
    String str = store.streamReadOnly().//
        sorted(Comparator.comparing(acc -> acc.getName())). //
        map(acc -> acc.getName() + ":" + acc.getBalance()).//
        collect(Collectors.joining(", "));
    System.out.println("Accounts: " + str);
  }

Clone this wiki locally