DZone
Java Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Java 10 Immutable/Unmodifiable Stream API Collectors

Java 10 Immutable/Unmodifiable Stream API Collectors

Java 10 now allows you to collect Stream pipelines into immutable data structures.

Grzegorz Piwowarek user avatar by
Grzegorz Piwowarek
·
Mar. 13, 19 · Java Zone · Presentation
Like (4)
Save
Tweet
13.47K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, while developing examples for the groupingBy() guide, I discovered the handy JDK 10 additions to the Stream API Collectors, allowing collecting Stream pipelines into unmodifiable data structures.

In this super short article, we'll have a closer look at them.

Immutable Collectors

By default, most Stream API Collectors represent mutable collection strategies — but what happens if one wants to collect elements to an immutable data structure?

The first thing that comes to mind is to pass an instance of an immutable collection to the Collectors.toCollection() collector, but it quickly turns out to be a path to nowhere since the provided collection is... immutable and can't be changed after creation:

Stream.of(42).collect(Collectors.toCollection(List::of));

// result
java.lang.UnsupportedOperationException
    at ...ImmutableCollections.uoe(ImmutableCollections.java:71)
    at ...ImmutableCollections$AbstractImmutableList.add(ImmutableCollections.java:77)
    at ...stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at ...stream.Streams$StreamBuilderImpl.forEachRemaining(Streams.java:411)


Technically, this wouldn't be a problem if Collections/Stream API was designed in an immutable-friendly manner, but we need to play the cards we were dealt.

Before JDK 10

Luckily, before JDK 10, the pragmatic solution to the above problem was quite straightforward. One could simply collect a Stream as always and then convert the result into an unmodifiable structure by leveraging the collectingAndThen collector:

var unmodifiableList = Stream.of(42)
  .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));


Another (in most cases - overkill) solution was to implement a custom collector, for example:

public class CustomUnmodifiableListCollector<T> 
  implements Collector<T, ArrayList<T>, List<T>> {

    private CustomUnmodifiableListCollector() {
    }

    public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
        return new CustomUnmodifiableListCollector<>();
    }

    @Override
    public Supplier<ArrayList<T>> supplier() {
        return ArrayList::new;
    }

    @Override
    public BiConsumer<ArrayList<T>, T> accumulator() {
        return ArrayList::add;
    }

    @Override
    public BinaryOperator<ArrayList<T>> combiner() {
        return (ts, ts2) -> Stream.concat(ts.stream(), ts2.stream())
          .collect(Collectors.toCollection(ArrayList::new));
    }

    @Override
    public Function<ArrayList<T>, List<T>> finisher() {
        return Collections::unmodifiableList;
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Set.of();
    }
}


After JDK 10

JDK 10 finally brought dedicated native collectors to the table, which makes the experience much smoother:

  1. toUnmodifiableList()
  2. toUnmodifiableMap()
  3. toUnmodifiableSet()

All of the above return new immutable implementations introduced in JDK 9.

So, the job is now as easy as:

var collect = Stream.of(42)
  .collect(Collectors.toUnmodifiableList());


...the interesting fact is that if you look at the implementation, you will see that they don't use builders, but simply repackage the result just like we did in the section above:

public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
    return new CollectorImpl<>(
      (Supplier<List<T>>) ArrayList::new, List::add,
      (left, right) -> { left.addAll(right); return left; },
      (list) -> (List<T>)List.of(list.toArray()), CH_NOID);
}


Sources

All the above examples can be found in my GitHub project.

API Java (programming language) Stream (computing)

Published at DZone with permission of Grzegorz Piwowarek, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Implementing RBAC Configuration for Kubernetes Applications
  • Ultra-Fast Microservices: When Microstream Meets Wildfly
  • Ultra-Fast Microservices: When Microstream Meets Payara
  • Comprehensive Guide to Jenkins Declarative Pipeline [With Examples]

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo