JetBrains Academy: Collectors - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Collectors

The product of squares:

Write a collector that evaluates the product of squares of integer numbers in a Stream<Integer>.

List<Integer> numbers = ...
long val = 
  numbers.stream()
    .collect(reducing(1, (productOfSquares, number) -> productOfSquares * number * number));

Palindrome or not:

Write a collector that partitions all words in a stream into two groups: palindromes (true) and usual words (false). The collector should return Map<Boolean, List>. All input words will be in the same case (lower).

Let's remind, a palindrome is a word or phrase which reads the same backward or forward, such as noon or level. In our case, a palindrome is always a word.

String[] words = ...
Map<Boolean, List<String>> palindromeOrNoMap = 
    Arrays.stream(words).collect(partitioningBy(word -> {
        String reverse = new StringBuilder(word).reverse().toString();
        return word.equals(reverse);
}));

The total sum of transaction by each account:

You have two classes:

  • Account: number: String, balance: Long
  • Transaction: uuid: String, sum: Long, account: Account

Both classes have getters for all fields with the corresponding names (getNumber(), getSum(), getAccount() and so on). Write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions.

List<Transaction> transactions = ...
Map<String, Long> totalSumOfTransByEachAccount = 
    transactions.stream()
                .collect(groupingBy(transaction -> transaction.getAccount().getNumber(), summingLong(Transaction::getSum)));

Counting clicks:

There is a LogEntry class for monitoring user activity on your site. The class has three fields:

  • created: Date - the date of creating log entry
  • login: String - a user login
  • url: String - a url that the user clicked

The class have getters for all fields with the corresponding names (getCreated(), getLogin(), getUrl()).

Write a collector that calculates how many times was each url clicked by users. The collector will be applied to a stream of log entries for creating a map: url -> click count.

List<LogEntry> logs = ...
Map<String, Long> clickCount = 
    logs.stream()
        .collect(groupingBy(LogEntry::getUrl, counting()));

⚠️ **GitHub.com Fallback** ⚠️