Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1.1K
Visualizações
Refactoring a nested loop into Java 8 streams collecting the outer objects

I have a loop which does what I want - it adds objects of type A to the results list:

ArrayList<A> results = new ArrayList<>();
for (A a: listOfA) {
  for (B b : a.getListOfB()) {
    if ("myString".equals(b.getMyString())) {
      results.add(a);
    }
  }
}

Now I'd like to refactor my code using Java 8 streams and I came up with this solution I'm stuck with because it collects objects of type B instead of A - List<A> results = ... is obviously wrong:

List<A> results = listOfA.stream()
  .flatMap(a -> a.getListOfB().stream())
  .filter(b -> "myString".equals(b.getMyString()))
  .collect(Collectors.toList());

How can I collect a list of type A using Java 8 streams?


I found many results here in SO looking for [java] nested foreach stream but I couldn't find anything that suits my needs.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You don't need flatMap here. Just apply a filter on the Stream<A>.

List<A> results = 
    listOfA.stream()
           .filter(a -> a.getListOfB()
                         .stream()
                         .anyMatch(b -> "myString".equals(b.getMyString())))
           .collect(Collectors.toList());

This is assuming you don't want to add an instance of A multiple times to the List if it has multiple B instances that match "myString".

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda