【问题标题】:how to find the position of an element that contains a certain character如何找到包含某个字符的元素的位置
【发布时间】:2021-12-05 18:28:04
【问题描述】:

改变主意,找到解决方案,谢谢

【问题讨论】:

  • 从您的描述中不清楚 list 包含哪个结构?它是某种具有名字和姓氏的 Person 类吗?要不然是啥?如果您遍历 regst 列表,那么 regst.getName(i).getFirstName() 没有任何意义。请描述列表中的内容?

标签: java methods chaining


【解决方案1】:

您不需要实现任何迭代逻辑,因为 ArrayList 已经拥有它。 只需从注册表中获取列表

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

然后只需遍历列表并返回所需名称的列表:

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;
}

或使用 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());
}

如果您需要获取该名称的第一个字母,您可以在 Name 类中实现这样的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    • 1970-01-01
    • 2021-07-25
    • 2014-03-02
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多