Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

241
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!