Skip to content

Accessing Objects

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

Accessing Objects

The API of the JACIS store provides several methods to access the stored objects. Here is a list of the most important access methods:

TV get(K key);

Return the object for the passed key.

List<TV> getAll();

Return all objects in the store as a List.

List<TV> getAll(Predicate<TV> filter);

Return all objects matching the passed filter in the store as a List.

Stream<TV> stream();

Return all objects in the store as a stream.

Stream<TV> stream(Predicate<TV> filter);

Return all objects in the store matching the passed filter as a stream.

boolean containsKey(K key);

Check if the store contains an object.

int size();

Return the number of objects in the store.

To show some of the access methods in action we 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