Question
How can I extend an ImmutableList with another List in Java?
import com.google.common.collect.ImmutableList;
import java.util.List;
public class Example {
public static void main(String[] args) {
ImmutableList<String> immutableList = ImmutableList.of("one", "two", "three");
List<String> additionalList = List.of("four", "five");
ImmutableList<String> extendedList = ImmutableList.<String>builder()
.addAll(immutableList)
.addAll(additionalList)
.build();
System.out.println(extendedList);
}
}
Answer
Extending an ImmutableList with elements from another List in Java is a common requirement when using the Guava library. ImmutableList instances are fixed-size and cannot be changed after creation, but you can create a new ImmutableList that includes elements from an existing one along with additional elements.
ImmutableList<String> extendedList = ImmutableList.<String>builder()
.addAll(immutableList)
.addAll(additionalList)
.build();
Solutions
- Use the ImmutableList.builder() method to create a new ImmutableList.
- Call addAll() for both the existing ImmutableList and the additional List elements.
- Call build() to finalize the new ImmutableList.
Common Mistakes
Mistake: Not using ImmutableList.builder() to create a new instance.
Solution: Always utilize the builder pattern to add elements to a new ImmutableList.
Mistake: Attempting to modify the original ImmutableList.
Solution: Remember that ImmutableLists are immutable; create a new list instead.
Helpers
- ImmutableList
- Java extend ImmutableList
- Guava ImmutableList
- add elements to ImmutableList
- Java list manipulation