我需要创建一个方法来搜索String数组是否在数组中存在specfic字符并返回该字符出现的出现次数的整数,我已查看其他帖子尝试自己解决但是他们都是int而不是String的数组
我有另一个类名,因此数组名称为Name。
public class Reg {
//Fields
private ArrayList<Name> Name;
//Constructors
public Reg() {
Name = new ArrayList<>();
}
//Methods
public int CountCharacterOccurrences (Char character){
}
}
名称等级:
public class Name implements Comparable<Name> {
//Fields
private String firstName;
private String familyName;
//Constructors
public Name() {
firstName = "";
familyName = "";
}
public Name(String firstName, String familyName) {
this.firstName = firstName;
this.familyName = familyName;
}
//Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public String getFirstName() {
return firstName;
}
public String getFamilyName() {
return familyName;
}
public String getFullName() {
if (firstName.equals("") && familyName.equals("")) {
return "";
} else {
return firstName + " " + familyName;
}
}
@Override
public String toString() {
return "Name:[firstName=" + firstName + ", familyName=" + familyName + "]";
}
}
如何添加一个接受char参数的CountCharacterOccurences方法,并返回一个表示发生次数的int。
答案 0 :(得分:0)
也许这就是你的意思:
class Reg{
private ArrayList<Name> names;
public Reg() {
names = new ArrayList<>();
}
public int countFirstNameOccurrences(char c) {
return names.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
}
public static void main(String[] args) {
Reg reg = new Reg();
reg.names.add(new Name("John", "Doe"));
reg.names.add(new Name("Johnny ", "Doe"));
reg.names.add(new Name("Richard", "Roe"));
reg.names.add(new Name("James", "Roe"));
reg.names.add(new Name("Jane", "Roe"));
System.out.println(reg.countFirstNameOccurrences('J'));
}
}
输出:
4
因为名单中的名字中有4个J(John,Johnny,James和Jane)