-1

need some help anything is appreciated!

I'm trying to create an method that takes a certain part of an array to make a new array that contains only those parts.

For example if I had an array with given array S = [“John Smith”, “Alice Huntington”, “George H. Baker”, “Helen Z. Gordon”], the program would return array T = [“J.S.”, “A.H.”, “G.H.B.”, “H.Z.G”].

I've done some searching online and found how charAt(0); I can take just the first initial but that's for a string and only the first letter. I don't know to get the last names or middle for example. Using an ArrayList is the right choice I think but I don't know how to transfer contents from one to the other.

  • 1
    You say you’re using an ArrayList, but also say you have an array. An ArrayList is not an array. Which is it? Note: Using a List is almost always preferable to using an array. – Bohemian Nov 01 '21 at 17:17

2 Answers2

2

A cleaner way to do it can be by using the Stream API.

import java.util.Arrays;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        String[] names = { "John Smith", "Alice Huntington", "George H. Baker", "Helen Z. Gordon" };
        String[] result = 
                Arrays.stream(names)
                    .map(
                            s -> Arrays.stream(s.split("\\s+"))
                                    .map(w -> w.substring(0, 1) + ".")
                                    .collect(Collectors.joining())
                    )
                    .toArray(String[]::new);

        // Display
        System.out.println(Arrays.toString(result));
    }
}

Output:

[J.S., A.H., G.H.B., H.Z.G.]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
2

You can use regex to get the job done:

list.replaceAll(s -> s.replaceAll("(.)[^ ]* ?", "$1."));

This works by using a lambda to replace each element of the list with its initial version.

The lambda works by matching every word, capturing the first letter as group 1, along with the trailing space (if any), and replacing the match with the captured initial and a dot.


Test code:

List<String> list = Arrays.asList("John Smith", "Alice Huntington", "George H. Baker", "Helen Z. Gordon");
list.replaceAll(s -> s.replaceAll("(.)[^ ]* ?", "$1."));
System.out.println(list);

Output:

[J.S., A.H., G.H.B., H.Z.G.]
Bohemian
  • 412,405
  • 93
  • 575
  • 722