This is best shown with an example:
Account a1 = new Account(1, "business", "num1"); Account a2 = new Account(2, "business", "num2"); Account a3 = new Account(3, "business", "num3"); List<Account> list = Lists.newArrayList(a1, a2, a3); List<Integer> ids = Lists.transform(list, new Function<Account, Integer>() { @Override public Integer apply(Account input) { return input.getId(); } }); assertThat(ids, contains(1, 2, 3)); a2.setId(12); assertThat(ids, contains(1, 12, 3));
Here a list of "Account"(s) is being transformed to a list of its corresponding ids. Any change in the id of the original objects is reflected in the transformed list.
Now, there are situations where an eager transformation may be desired - for eg. needing to cache the transformed list, or serializing the transformed list. The way to force an eager transformation is to make a copy of the lazy list, using another utility method provided by the Lists class:
Lists.newArrayList(ids)
No comments:
Post a Comment