Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4536

Get the Initials of a Name in Java

$
0
0

1. Introduction

When handling names, it can be beneficial to shorten them into abbreviated strings using each word’s first character. In this tutorial, let’s look at different ways to implement this functionality in Java.

2. Assumptions

When creating abbreviations, we only consider words that begin with the alphabet. Any other words are excluded from the process. Additionally, the abbreviation may result in an empty string with no valid words. Furthermore, we convert the entire string to uppercase.

3. Using Loops

We can split the text by spaces and use a for loop to iterate over each word. Subsequently, we can take the first character of each valid word and build the initials:

String getInitialUsingLoop(String name) {
    if (name == null || name.isEmpty()) {
        return "";
    }
    String[] parts = name.split("\\s+");
    StringBuilder initials = new StringBuilder();
    for (String part : parts) {
        if (part.matches("[a-zA-Z].*")) {
            initials.append(part.charAt(0));
        }
    }
    return initials.toString().toUpperCase();
}

In the above code, we check if a word starts with the alphabet using a regex and then extract the first character to form the abbreviation.

We can write a unit test to check different cases using JUnit:

@ParameterizedTest
@CsvSource({"John F Kennedy,JFK", ",''", "'',''", "Not Correct   88text,NC", "michael jackson,MJ", "123,''", "123 234A,''", "1test 2test, ''"})
void getInitialFromName_usingLoop(String input, String expected) {
    String initial = getInitialUsingLoop(input);
    assertEquals(expected, initial);
}

In the above test case, we utilized JUnit’s parameterized test feature to specify multiple input and expected output combinations. As a result, we can ensure comprehensive coverage and validation of the functionality under different conditions.

4. Using StringTokenizer

We can use the StringTokenizer to split the text into words. Let’s look at the implementation:

String getInitialUsingStringTokenizer(String name) 
    if (name == null || name.isEmpty()) {
        return "";
    }
    StringTokenizer tokenizer = new StringTokenizer(name);
    StringBuilder initials = new StringBuilder();
    while (tokenizer.hasMoreTokens()) {
        String part = tokenizer.nextToken();
        if (part.matches("[a-zA-Z].*")) {
            initials.append(part.charAt(0));
        }
    }
    return initials.toString().toUpperCase();
}

This code is similar to the previous implementation, except we use StringTokenizer instead of the split() method.

We can utilize the same parameterized test as before for this method.

5. Using Regular Expressions

Another way to implement this functionality is by using regular expressions. We can capture the first character of each valid word by using a Regex Capture:

String getInitialUsingRegex(String name) {
    if (name == null || name.isEmpty()) {
        return "";
    }
    Pattern pattern = Pattern.compile("\\b[a-zA-Z]");
    Matcher matcher = pattern.matcher(name);
    StringBuilder initials = new StringBuilder();
    while (matcher.find()) {
        initials.append(matcher.group());
    }
    return initials.toString().toUpperCase();
}

Similarly, we can create a test case to validate the implementation. 

6. Using the Stream API

We can also use the functional programming-based Stream API, which has been available since Java 8. Now, let’s delve into the implementation:

String getInitialUsingStreamsAPI(String name) {
    if (name == null || name.isEmpty()) {
        return "";
    }
    return Arrays.stream(name.split("\\s+"))
      .filter(part -> part.matches("[a-zA-Z].*"))
      .map(part -> part.substring(0, 1))
      .collect(Collectors.joining())
      .toUpperCase();
}

In this scenario, we combined the filter(), map(), and collect() methods to accomplish the goal. We can use a similar parameterized test to verify this implementation as well.

7. Conclusion

This article discussed various methods for extracting the initials from a name in Java. These methods can also generate acronyms for any text, not just names. Furthermore, we explored the traditional loop-based approaches, regular expression, and more functional programming approaches to achieve the same outcome. Depending on the specific scenario, developers can choose the approach that best suits their needs.

As always, the sample code used in this tutorial is available over on GitHub.

 

       

Viewing all articles
Browse latest Browse all 4536

Trending Articles