Luke Hetherington
Luke Hetherington

Reputation: 37

How to just get last letter of string instead of whole string

I currently have a function that searches an array of strings and accepts a char argument and returns an int signalling the number of occurrences ending with the character given, and I need to modify it so it only counts the occurrences that end in that specific character.

For example:

If I had Luke and Jen and i was looking for 'e' then the output would be one as luke is the only one that ends in 'e'

This is my current code.

public int countFirstNameOccurrences(char c) {
        return Reg.stream()            // get Stream<Name>
                .map(Name::getFirstName) // convert Stream<Name> to Stream<String> using Name's firstName
                .mapToInt(s -> s.length() - s.replace(String.valueOf(c), "").length()) // calculate every occurrence c in each firstName and get an IntStream
                .sum();                  // sum all the values
    }

Upvotes: 2

Views: 852

Answers (2)

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

I know you have an accepted answer, but some people unfortunately are forced to use Java versions lower than 8, so here's an alternative without using a stream:

public static int count(char c) {
    int count = 0;
    for (String name : names) {
        if (name.charAt(name.length() - 1) == c) {
            count++;
        }
    }
    return count;
}

Simple example here.

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56463

Either this:

public int countFirstNameOccurrences(char c) {
        String character = String.valueOf(c); // character represented as a String
        return Reg.stream()  // Stream<Name>
                  .map(Name::getFirstName) // Stream<String>
                  .mapToInt(n -> n.endsWith(character)? 1 : 0) // IntStream
                  .sum(); // int
}

or as Alexis has suggested but you'd need to cast to int as count returns a long type.

public int countFirstNameOccurrences(char c) {
        return (int)Reg.stream() //Stream<Name>
                       .map(Name::getFirstName) // Stream<String>
                       .filter(n -> n.charAt(n.length() -1) == c) // Stream<String>
                       .count(); // long
}

Upvotes: 3

Related Questions