Over a million developers have joined DZone.

Groovy Goodness — Unmodifiable Collections [Snippet]

DZone's Guide to

Groovy Goodness — Unmodifiable Collections [Snippet]

Here is a new way to make your collections immutable. Read on for details and an example!

· Java Zone ·
Free Resource

Delivering modern software? Atomist automates your software delivery experience.

When we wanted to create collections in Groovy that were unmodifiable, we could use asImmutable. Since Groovy 2.5.0, we can also use the asUnmodifiable method on collections. The method can be applied to all Collection types, including Map.

In the following example, we use asUnmodifiable on a List and Map:

import static groovy.test.GroovyAssert.shouldFail

// Create List that is unmodifiable.
def list = ['Groovy', 'Gradle', 'Asciidoctor', 'Micronaut'].asUnmodifiable()

shouldFail(UnsupportedOperationException) {
    // We cannot add new items.
    list << 'Java'

    // We cannot change items.
    list[0] = 'Java'

// Create Map that is unmodifiable.
def data = [name: 'Messages from mrhaki', subject: 'Gr8 stuff'].asUnmodifiable()

shouldFail(UnsupportedOperationException) {
    // We cannot add a new key.
    data.subject = 'Dev subjects'

    // We cannot change the value of a key.
    data.blog = true

Written with Groovy 2.5.0.

Start automating your delivery right there on your own laptop, today! Get the open source Atomist Software Delivery Machine.

java ,groovy ,collections ,immutable ,code

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}