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?
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]]
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);
...
}