CodexBloom - Programming Q&A Platform

Getting 'IndexOutOfBoundsException' When Using Java Streams with Custom Collector

๐Ÿ‘€ Views: 401 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-11
java streams collectors exception Java

I'm stuck on something that should probably be simple. I'm sure I'm missing something obvious here, but I'm working with an `IndexOutOfBoundsException` when I attempt to collect elements from a `List` into a custom data structure using Java Streams. I'm using Java 11 and have created a custom collector that aims to aggregate results into a `Map<String, List<String>>`. Hereโ€™s the code I'm working with: ```java import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> items = List.of("apple", "banana", "apple", "orange", "banana", "kiwi"); Map<String, List<String>> collected = items.stream() .collect(Collectors.toMap( item -> item, item -> List.of(item), // This part seems to be causing the scenario (existing, replacement) -> { existing.addAll(replacement); return existing; } )); } } ``` When I run this code, I receive the following behavior: ``` Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 ``` I suspect the scenario arises from how I'm adding elements to the `existing` list in the merge function of `Collectors.toMap()`. I've also tried initializing a mutable list but keep running into the same `IndexOutOfBoundsException`. Hereโ€™s what I tried instead: ```java Map<String, List<String>> collected = items.stream() .collect(Collectors.toMap( item -> item, item -> new ArrayList<>(List.of(item)), (existing, replacement) -> { existing.addAll(replacement); return existing; } )); ``` This still throws an exception. Iโ€™m not sure if the question lies in how Iโ€™m creating the list or if itโ€™s in how Iโ€™m merging the lists. Any insights on how I can resolve this scenario? Is there a better approach? I'm developing on macOS with Java. Any help would be greatly appreciated!