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

194
Visualizações
Get multiple elements from list by indices in constant time

What is the best way to get multiple elements from a list by their indices in constant time?

If I've an array:

List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");

And I've an list/array with indices:

List<Integer> indices = new ArrayList<>();
indices.add(0);
indices.add(2);
indices.add(3);

How can I get a,c,d in constant time? I need something like this:

List<String> filtered = list.filterByIndex(indices);
filtered.stream().forEach(x -> System.out.print(x));
// output:"acd"

UPDATE: The printing of the items doesn't have to be in constant time of course, only the collecting of items. The code above of printing the elements is just for demonstrating purposes only.

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

0

I suggest:

    List<String> filtered = indices.stream()
            .map(list::get)
            .collect(Collectors.toList());

The result is the desired:

[a, c, d]

Assuming the list has constant-time access (as an ArrayList has), this runs in time that is linear in the number of elements requested (length of indices), but does not increase with the length of the list list. As has been discussed in comments, this is the best we can do.

Edit: Honestly I don’t know whether the collecting step above is in linear time in the number of collected elements. Possibly extensions of list capacity cost time, and probably this doesn’t take more than linear time. If we need to be sure, we need to collect this way instead:

            .collect(Collectors.toCollection(() -> new ArrayList<>(indices.size())));

This makes sure a list with appropriate capacity is allocated from the outset so no extensions will be needed.

over 4 years ago · Santiago Trujillo Relatório

0

To create a list:

List<String> filtered = new ArrayList<>();
indices.forEach(index -> filtered.add(list.get(index)));

System.out.println(filtered);

Stream and map solution

List<String> filtered = indices.stream()
        .map(index -> list.get(index))
        .collect(Collectors.toList());

If you need only string you can do it with StringBuilder

StringBuilder sb = new StringBuffer();
indices.forEach(index -> sb.append(list.get(index)));

System.out.println(sb.toString());
over 4 years ago · Santiago Trujillo Relatório

0

You might do something like this:

IntStream.range(0, list.size())
       .boxed()
       .filter(indices::contains)
       .map(list::get)
       .forEach(System.out::println);
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