He visto tu pregunta y me ha picado la curiosidad, entonces desarrollé un ejemplo rápido para evaluar cual seria la mejor opción. He intentado recrear tu pregunta inicial y me he montado unas pruebas con un arreglo de 20 entradas, la única salvedad es que optimice un pelin tu método de búsqueda con la expresión lamda. Prueba tu también y valoramos los resultados. Aunque no es una buena practica monte todo en un solo archivo.
import java.util.ArrayList;
class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Main {
// main method
public static void main(String[] args) {
ArrayList<Person> data = buildData();
for (int i = 0; i < 5; i++){
System.out.println("-------------------");
System.out.println("Iteration " + (i + 1));
System.out.println("-------------------");
// select a random number for concat with name to search
int randomNumber = (int)(Math. random()*20+1);
System.out.println("Searching: name"+randomNumber);
// Run find method with bucle
long startTimeHS = System.currentTimeMillis();
if (findName(data, "name" + randomNumber)) {
System.out.print("Find with bucle in ");
} else {
System.out.print("Not found with bucle in ");
}
System.out.println(System.currentTimeMillis() - startTimeHS + "ms");
// Run find method with lamda
long startTimeHSLamda = System.currentTimeMillis();
if (findNameWithLambda(data, "name" + randomNumber)) {
System.out.print("Find with lamda in ");
} else {
System.out.print("Not found with lamda in ");
}
System.out.println(System.currentTimeMillis() - startTimeHSLamda + "ms");
}
}
public static ArrayList<Person> buildData() {
ArrayList<Person> data = new ArrayList<>();
data.add(new Person("name1", 24));
data.add(new Person("name2", 15));
data.add(new Person("name3", 10));
data.add(new Person("name4", 80));
data.add(new Person("name5", 44));
data.add(new Person("name6", 34));
data.add(new Person("name7", 76));
data.add(new Person("name8", 22));
data.add(new Person("name9", 33));
data.add(new Person("name10", 23));
data.add(new Person("name11", 76));
data.add(new Person("name12", 22));
data.add(new Person("name13", 55));
data.add(new Person("name14", 56));
data.add(new Person("name15", 98));
data.add(new Person("name16", 65));
data.add(new Person("name17", 43));
data.add(new Person("name18", 11));
data.add(new Person("name19", 21));
data.add(new Person("name20", 44));
return data;
}
public static boolean findName(ArrayList<Person> people, String name) {
for (Person person : people)
if (person.getName().equals(name))
return true;
return false;
}
public static boolean findNameWithLambda(ArrayList<Person> people, String name) {
return people.stream().anyMatch(p -> p.getName().equals(name));
}
}
Resultados para 5 iteraciones: