简体   繁体   English

是否有 function 来计算 Java 中每个循环的迭代次数?

[英]Is there a function to count iterations of for each loops in Java?

I'm starting out on Java and I'm creating a basic phonebook application.我从 Java 开始,我正在创建一个基本的电话簿应用程序。 I'd like to implement a "Search Contacts" function that searches through an ArrayList of contacts and returns a count of how many contacts match the user-inputted String using a for each loop and if statement.我想实现一个“搜索联系人”function,它搜索联系人的 ArrayList,并使用每个循环和 if 语句返回与用户输入的字符串匹配的联系人数量。 Question is, is it possible to receive a count of the contacts that match the user's search input without first defining an int - say, int counter = 0;问题是,是否可以在不首先定义 int 的情况下接收与用户搜索输入匹配的联系人计数 - 例如, int counter = 0; - and then updating it within the if statement? - 然后在 if 语句中更新它?

Below is an example of the only method I know could work to tally the number of matching contacts:以下是我所知道的唯一可以计算匹配联系人数量的方法的示例:

int counter = 0;

System.out.println("Please enter name of contact: ");

String nameRequest = scanner.nextLine();


for (Contact c: contactList) {
    if (nameRequest.equals(c.getName())){
    counter++;
    System.out.println(counter + " contact(s) found"
    System.out.println("Name: " + c.getName());
    }
}

Extras: How could I go about so the code also returns contacts that are only a partial match?附加功能:我怎么能 go 这样代码还返回仅部分匹配的联系人? eg User inputs "Michael" but there are no contacts that only contain "Michael".例如,用户输入“Michael”,但没有包含“Michael”的联系人。 There are however contacts called "Michael B Jordan" and "Michael Schumacher" which I'd like returned for the partial match.然而,我希望在部分比赛中返回名为“Michael B Jordan”和“Michael Schumacher”的联系人。

Thanks in advance!提前致谢!

Using the counter variable it is a standard for people in this cases.在这种情况下,使用计数器变量是人们的标准。 But if it is for study purposes, you can achieve this with Lambda, where you first select the contacts, get the names and store in a temporary list:但如果是出于学习目的,您可以使用 Lambda 来实现此目的,您首先 select 联系人,获取名称并存储在临时列表中:

List<String> contactsFound = contactList.stream()
    .map(Contact::getName)
    .filter(nameRequest::equals)
    .collect(Collectors.toList());

System.out.println(contactsFound.size() + " contact(s) found");

contactsFound.forEach(contactName -> System.out.println("Name: " + contactName));

Here is the same basic solution as Brothers answer but with a for loop (as in the question):这是与兄弟回答相同的基本解决方案,但带有 for 循环(如问题所示):

List<String> contactsFound = new ArrayList<>();
for (Contact c: contactList) {
    if (c.getName().toLowerCase().contains(nameRequest.toLowerCase())){
        contactsFound.add(c.getName());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM