'How obtain a Set of Strings from a Map of objects with a string property

I need to get a Set<String> with the accountNumbers from the given Map<String, Account> and filter the map contents by retaining only active accounts (active == true) so that there will be no inactive accounts.

Account class has the following attributes:

private String number;
private String owner;
private double balance;
private boolean active = true;

My solution so far looks like this:

public Set<String> getAccountNumbers() {
    return new HashSet<String>(accounts.values().stream().filter(Account::isActive));
}

I tried casting, but that didn't seem to work. Can somebody tell me, how I access the attribute number from here on?



Solution 1:[1]

You have to apply map in order to transform the stream of accounts Stream<Account> into a stream of strings Stream<String>. And then apply the terminal operation collect to obtain a Set as a result of the execution of stream pipeline.

Your attempt to pass the stream to the constructor of the HashSet is incorrect (it expects a Collection, not a Stream) and unnecessary.

Note: stream without a terminal operation (like collect, count, forEach, etc.) will never get executed. map and filter are called intermediate operations.

public Set<String> getAccountNumbers() {
    return accounts.values().stream()    // Stream<Account>
            .filter(Account::isActive)
            .map(Account::getNumber)     // Stream<String>
            .collect(Collectors.toSet());
}

For more information on streams take a look at this tutorial

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1