user15846058
user15846058

Reputation:

how to find the position of an element that contains a certain character

So I have a list that stores names with a first and a family name. (this list is called regst) And I already have some methods that separates the first name and last name and also a set and get method.

I have to execute a code that returns a string that represent each name in my regst list that has a first name containing either of the characters "a" or "e". Also that gets these names and outputs the first letter of first and family name.

So far I created this for loop! My problem is how to select the names that contains these characters and returns a string where it get the first letter of the first name and family name? Generally: how to find the position of an element that contains a certain character?

for (int i = 0; i < regst.size(); i++) {            
    if (regst.getName(i).getFirstName().contains("a") || regst.getName(i).getFirstName().contains("e")) {
        System.out.println("All the first names that contains the characters a or e: "
                 + regst.getName(i).getFirstName().contains("a") 
                 + regst.getName(i).getFirstName().contains("e"));
    } else {
        return "";
    }
}

Upvotes: 0

Views: 242

Answers (1)

Vitaly Kolesnikov
Vitaly Kolesnikov

Reputation: 265

You don`t need to implement any iteration logic as ArrayList already has it. Just get a list from register

List<Name> list = register.getList(); // you need a getter for this

Then just iterate through list and return list of needed names:

public List<Name> findNames(List<Name> list) {
    List<Name> result = new ArrayList<>();
    for (Name name : list) {
        if (name.getFirstName().contains("a") || name.getFirstName().contains("e")) {
            result.add(name);
        }
    }
    return result;
}

Or using Stream API:

public static List<Name> findNames(List<Name> list) {
return list.stream()
    .filter(name -> name.getFirstName().contains("a") || name.getFirstName().contains("e"))
    .collect(Collectors.toList());
}

If you need to get first letter of that names, you can implement such method in Name class:

public String getInitials() {
    return firstName.charAt(0) + "." + familyName.charAt(0) + ".";
}

Upvotes: 0

Related Questions