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

166
Visualizações
LongStream filtering

I have two Java LongStreams and I want to remove values which are present in one stream from the other.

LongStream stream 1 = ...
LongStream stream 2 = ...

stream2  = stream2.filter(e-> stream1.contains(e));

The LongStream does not have a contains method and I dont know how to use anyMatch in this case because the value to be checked is coming from another stream and is not in a variable or constant.

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

0

You could collect to a Set and use contains:

LongStream stream1 = ...
LongStream stream2 = ...

Set<Long> set1 = stream1.boxed().collect(Collectors.toSet());

stream2 = stream2.filter(set1::contains);
over 4 years ago · Santiago Trujillo Relatório

0

Well, you cannot search in the Stream as long as Stream is an unfinished set of pipelines, i.e. operations. It makes no sense to compare it with such Stream.

The next thing that seems odd to me is probably a typo. I assume you want to search in the stream1 instead of stream2, hence:

stream2 = stream2.filter(e -> stream1.contains(e));

The only way is to compare a LongStream with a collection which is optimized for such search. I assume you want to continue the stream1 after you perform the search, so perform these steps:

  1. Close stream1 converting it to a List<Long> list1.
  2. Perform the search in stream2 using list1 from stream1.
  3. Open stream1 again for further processing.
LongStream stream1 = ...
LongStream stream2 = ...

List<Long> list1 = stream1.boxed()                       // list1 from stream1 ..
                          .collect(Collectors.toList()); // .. which also closes stream1

stream2  = stream2.filter(list1::contains);              // perform search

stream1 = list1.stream().mapToLong(l -> l);              // open stream1 as LongStream

Edit: Use Set for better performance as @fps suggests in his answer.

over 4 years ago · Santiago Trujillo Relatório

0

Why use streams at all?

Collections have the retainAll(Collection) method, that does just what you need, if i am not mistaken...
(Or removeAll(Collection) just a bit above...)

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