Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

512
Vistas
Java Streams: filter().count() vs anyMatch()

I want to find if a stream of strings has at least one occurrence of another String in a Set<String>. I came up with two solutions.

Performance wise, which approach is the best/recommended?

1)

return source.stream().filter(this::streamFilter).count() > 0;

2)

return source.stream().anyMatch(this::streamFilter);

Here's streamFilter method:

private boolean streamFilter(String str) {
    return filterKeywords.contains(str.toLowerCase());
}

filterKeywords: private Set<String> filterKeywords;

Or is there better approach than this?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You should use anyMatch(this::streamFilter), look at the API on the anyMatch method below (emphasis mine) as it may not evaluate all elements of the stream where as count() obviously iterates the whole stream of elements.

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

The point is some of the stream methods like findFirst(), anyMatch(), findAny(), etc.. perform short-circuiting operations i.e., they may not evaluate all elements of the stream and you can refer here for more details.

over 4 years ago · Santiago Trujillo Denunciar

0

anyMatch doesn't always execute all the stream. It is the best approach.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda