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.

For the examples below we use the same class for the store entry as in the Getting Started chapter. 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:

    // Now we show some examples how to use the stream API to access objects from the store:
    container.withLocalTx(() -> {

      // using stream methods (compute the total balance of all stored accounts):
      System.out.println("total balance=" + store.stream().mapToLong(Account::getBalance).sum());

      // using a filter (count accounts with a balance > 500):
      System.out.println("#>500=" + store.stream(acc -> acc.getBalance() > 500).count());

      // looping through the elements (adding writing an output)
      store.stream().forEach(acc -> {
        System.out.println(" - account " + acc.getName() + ": balance = " + acc.getBalance());
      });

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

Next Chapter: Modifying Objects