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

242
Visualizações
Grouping only consecutive elements based on property using Java Streams

I have list of objects, each object having an id. I want to group elements by their id given they are consecutive. Like, if objects are:

(id1, id1, id1, id2, id2, id3, id3, id2, id2, id4)

then groups must be:

(id1, id1, id1), (id2, id2), (id3, id3), (id2, id2), (id4)

Can this be achieved by Java Streams API?

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

0

This is very possible using mutable reduction resulting in the List<List<String>>. For better readability, I recommend to split into methods:

List<List<String>> newList = list.stream().collect(
    ArrayList::new,
    (lists, string) -> {
        if (lists.isEmpty()) {
            withNewList(lists, string);
        } else {
            withNewString(lists, string);
        }
    },
    ArrayList::addAll
);
// adds a new inner list with a single item (string)
static void withNewList(ArrayList<List<String>> lists, String string) {
    List<String> newList1 = new ArrayList<>();
    newList1.add(string);
    lists.add(newList1);
}
static void withNewString(ArrayList<List<String>> lists, String string) {
    // if the last inserted list has a same item
    List<String> lastList = lists.get(lists.size() - 1);   
    if (lastList.contains(string)) {
        // append it to the last inner list
        lastList.add(string);
    } else {
        // or else create a new list with a single item (string)
        withNewList(lists, string);
    }
}

Considering the following list input:

List<String> list = List.of(
    "id1", "id1", "id1", "id2", "id2", "id3", "id3", "id2", "id2", "id4");

... when you print the result out, the output looks like:

[[id1, id1, id1], [id2, id2], [id3, id3], [id2, id2], [id4]]

over 4 years ago · Santiago Trujillo Relatório

0

For easy navigation to the last (previous) item, I'd use a LinkedList of LinkedLists:

public static void main(String[] args) {
    ...
    Stream.of(id1, id1, id1, id2, id2, id3, id3, id2, id2, id4)
            .sequential() // order is essential
            .collect(LinkedList::new, (listOfLists, object) -> {
        if (listOfLists.isEmpty() || listOfLists.getLast().getLast() != object) {
            listOfLists.add(new LinkedList<>(List.of(object)));
        } else {
            listOfLists.getLast().add(object);
        }
    }, List::addAll);
    ...
}
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