DZone
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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Databases
  4. 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 · Presentation
Like (4)
Save
Tweet
Share
13.73K 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

  • Fixing Bottlenecks in Your Microservices App Flows
  • Best Navicat Alternative for Windows
  • What Are the Different Types of API Testing?
  • Seamless Integration of Azure Functions With SQL Server: A Developer's Perspective

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • 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: