使用ONE方法循环ArrayList

时间:2016-12-06 08:38:22

标签: java loops arraylist

有人可以通过列表中的一个循环帮助我如何缩短此代码,deleteFromList()和increaseAge()都可以使用吗?

private void deleteFromList() {
    System.out.println("Type the name of the person you want to delete: ");
    String nameOfPerson = keyboard.nextLine();
    for (int i = 0; i < allPersons.size(); i++) {
        if (allPersons.get(i).getName().equalsIgnoreCase(nameOfPerson)) {
            allPersons.remove(i);
            System.out.println("The person has been deleted!");
        }
    }
}


private void increaseAge() {
    System.out.println("Type in the persons name: ");
    String nameOfPerson = keyboard.nextLine();
    for (int i = 0; i < allPersons.size(); i++) {
        if (allPersons.get(i).getName().equalsIgnoreCase(nameOfPerson)) {
            Person person = allPersons.get(i);
            person.setAge();
            System.out.println("Persons age have been changed");
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,那么您希望避免两种方法之间的重复迭代和比较逻辑。好消息是,如果您使用的是Java 8,则根本不需要循环:

private void deleteFromList() {
    System.out.println("Type the name of the person you want to delete: ");
    String nameOfPerson = keyboard.nextLine();
    allPersons.removeIf(p -> p.getName().equalsIgnoreCase(nameOfPerson));
}

private void increaseAge() {
    System.out.println("Type in the persons name: ");
    String nameOfPerson = keyboard.nextLine();
    allPersons.stream()
            .filter(p -> p.getName().equalsIgnoreCase(nameOfPerson))
            .forEach(Person::setAge);
}

答案 1 :(得分:1)

也许以下内容可能会有所帮助?名称应该可以优化;-) 使用一般方法handlePerson,以便您可以根据需要添加特定的消费者。

public void handlePerson(String personName, Consumer<Person> personConsumer) {
    allPersons.stream()
        .filter(p -> p.getName().equalsIgnoreCase(personName))
        .forEach(personConsumer);
}


public void increaseAge() {
    System.out.println("Type in the persons name: ");
    handlePerson(keyboard.nextLine(), Person::setAge));
    // or if you really want to do it all in the consumer:
    handlePerson(keyboard.nextLine(), p -> { 
        p.setAge(); 
        System.out.println("Persons age have been changed");
    });
}

public void deletePerson() {
    System.out.println("Type in the persons name: ");
    String personName = keyboard.nextLine();
    // of course no way to handle deletion via consumer ;-)
    if (allPersons.removeIf(p -> p.getName().equalsIgnoreCase(personName))) {
        System.out.println("The person has been deleted!");
    }

}

如果您经常使用Predicate,则可能还需要单独介绍p.getName().equalsIgnoreCase(personName)