Birdy
Birdy

Reputation: 45

Return the number of different initial letters (case-insensitive) of all names? (Java)

I have .getOwner and .displayname and an Array q for disposal.

How can I return the number of different initial letters (case-insensitive) of all names using streams?

I tried it that way:

return q.stream()
        .map(n -> n.getOwner().display_name.length() != 0 n.getOwner().display_name.charAt(0) : ' ')
        .distinct();

It's not working.

Upvotes: 1

Views: 91

Answers (1)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59986

I think(you need two more steps) filter if it is an alphabetic to avoid space from condition, and count in the end:

long count = q.stream()
        .map(n -> n.getOwner().display_name.length() != 0 ? Character.toLowerCase(n.getOwner().display_name.charAt(0)) : ' ')
        .distinct()
        .filter(Character::isAlphabetic)
        .count();

if you accept all characters except space then you can replace filter with:

.filter(n -> n != ' ')

Note: I would recommend to replace display_name by private String displayName; and use getter and setters instead of calling the attribute directly.


An ideal Solution:

long count = q.stream()
        .map(ClassName::getOwner)
        .map(Owner::getDisplayName)
        .filter(dn -> dn.length() > 0)
        .map(dn -> Character.toLowerCase(dn.charAt(0)))
        .distinct()
        .count();

Upvotes: 3

Related Questions