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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Domain-Driven Design: Manage Data With Jakarta Data and JNoSQL
  • Understanding and Learning NoSQL Databases With Java: Three Key Benefits
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL

Trending

  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  1. DZone
  2. Coding
  3. Frameworks
  4. Hidden Treasures of Eclipse Collections - Part 1

Hidden Treasures of Eclipse Collections - Part 1

There are some hidden gems in the Eclipse Collections framework.

By 
Nikhil Nanivadekar user avatar
Nikhil Nanivadekar
·
Updated Jan. 14, 21 · Presentation
Likes (6)
Comment
Save
Tweet
Share
14.4K Views

Join the DZone community and get the full member experience.

Join For Free

Eclipse Collections is an open-source Java Collections framework. Please refer to the resources at the end of the blog for more information about the framework. In this blog, I am going to demonstrate five lesser-known features of the framework.

  • distinct(): When you want to get unique items in your List, the typical way to get them is to add your List to a Set. However, you lose the original order and end up with an unpredictable order of a hash table. Sometimes, you need to preserve the order in which we have visited the unique elements. We developed distinct() for this use case. When you call distinct() on an Eclipse Collections MutableList, the result is a List of unique elements.
    @Test
    public void distinct()
    {
        MutableList<Integer> integers = Lists.mutable.with(
                1, 2, 2, 3, 3, 3, 4, 4, 4, 4);
        Assert.assertEquals(
                Lists.mutable.with(1, 2, 3, 4), 
                integers.distinct());
    }

    If you cannot convert your original List into an Eclipse Collections List, you can use ListAdapter or ListIterate to get the same API.
    @Test
    public void distinctNonEclipseCollectionsList()
    {
        List<Integer> integersLinkedList = new LinkedList<>(integers);
        Assert.assertEquals(
                Lists.mutable.with(1, 2, 3, 4),
                ListAdapter.adapt(integersLinkedList).distinct());
        Assert.assertEquals(
                Lists.mutable.with(1, 2, 3, 4),
                ListIterate.distinct(integersLinkedList));
    }

    If you need distinct() to be available for lazy evaluation, it is available on our LazyIterable as well.
    @Test
    public void distinctAsLazy()
    {
        MutableList<String> distinctStrings = integers.asLazy()
                .distinct()
                .collect(String::valueOf)
                .toList();
        Assert.assertEquals(
                Lists.mutable.with("1", "2", "3", "4"),
                distinctStrings);
    }
  • selectInstancesOf(): If you want to filter and return only the instances of a particular class, you can use selectInstancesOf().
    @Test
    public void selectInstancesOf()
    {
        MutableList<Number> numbers = Lists.mutable.with(
                1.0, 2, 3.0, 4.0, 5);
        MutableList<Integer> integers = numbers
                .selectInstancesOf(Integer.class);
        Assert.assertEquals(Lists.mutable.with(2, 5), integers);
    }

    If you cannot use an Eclipse Collections interface, you can always wrap your collections with our adapters or use our static utility Iterate to get the same API.
    @Test
    public void selectInstancesOf()
    {
        List<Number> numberList = new ArrayList<>(numbers);
        MutableList<Integer> integersUsingAdapter = ListAdapter
                .adapt(numberList)
                .selectInstancesOf(Integer.class);
        Assert.assertEquals(
                Lists.mutable.with(2, 5), 
                integersUsingAdapter);
    
        Collection<Integer> integersUsingIterate = Iterate
                .selectInstancesOf(numberList, Integer.class);
        Assert.assertEquals(
                Lists.mutable.with(2, 5), 
                integersUsingIterate);
    }
  • chunk(): If you want to divide your iterable into multiple iterables of a particular size, you can use chunk().
    @Test
    public void chunk()
    {
        MutableList<Integer> integers = Lists.mutable.with(
                1, 2, 3, 4, 5);
        MutableList<MutableList<Integer>> expectedChunked =
                Lists.mutable.with(
                        Lists.mutable.with(1, 2),
                        Lists.mutable.with(3, 4),
                        Lists.mutable.with(5));
        Assert.assertEquals(
                expectedChunked, 
                integers.chunk(2));
    }

    If you cannot use an Eclipse Collections interface, you can always wrap your collections with our adapters or use our static utility Iterate to get the same API.
    @Test
    public void chunk()
    {
        List<Integer> integerList = new ArrayList<>(integers);
    
        RichIterable<RichIterable&lt;Integer>> chunkUsingAdapter =
            ListAdapter
                .adapt(integerList)
                .chunk(2);
        Assert.assertEquals(
                expectedChunked,
                chunkUsingAdapter);
    
        RichIterable<RichIterable<Integer>> chunkUsingIterate = 
            Iterate
                .chunk(integerList, 2);
        Assert.assertEquals(
                expectedChunked,
                chunkUsingIterate);
    }
  • as vs. to naming convention: In Eclipse Collections, we try to follow common conventions like the ones described in this blog. In Eclipse Collections, methods that start with the word “as” always take constant time and create constant garbage. Usually, that means returning a wrapper object. Some examples:
    • asUnmodifiable() – returns collection wrappers that throw on mutating methods
    • asSynchronized() – returns collection wrappers that grab a lock before delegating
    • asLazy() – returns a wrapper that supports lazy evaluation, by deferring evaluation of non-terminating operations and only evaluating when a terminating operation is encountered
    • asReversed() – returns a lazy wrapper around a list that iterates in reverse order when computation is forced
    • asParallel()(Beta) – returns a lazy wrapper that supports parallel execution

    In Eclipse Collections, methods that start with the word “to” can take more time and create more garbage. Most of the time, that means creating a new collection in linear time. In the case of sorted collections, that grows to  O(n log n). Some examples:
  • toList() – always creates a new copy, even when called on lists
  • toSet(), toBag(), toStack(), toMap(), toArray() – O(n) in time and memory
  • toSortedList(), toSortedListBy(), toSortedSet(),toSortedSetBy(), toSortedMap() – O(n log n) time
  • toImmutable() – O(n) time on mutable collections
  • toReversed() – same as asReversed() but will have eager evaluation
  • toString() – yes, it counts!

Summary

In this blog, I explained a few lesser-known features of Eclipse Collections : distinct(),  partition(), selectInstancesOf(),chunk() , and as() vs. to()method naming conventions.

I hope you found this post informative. If you have not used Eclipse Collections before, give it a try. There are few resources below. Make sure you show us your support and put a star on our GitHub Repository

Eclipse Collections Resources

Eclipse Collections comes with its own implementations of List, Set, and Map. It also has additional data structures like Multimap, Bag, and an entire Primitive Collections hierarchy. Each of our collections has a rich API for commonly required iteration patterns.

  • Website
  • Source code on GitHub
  • Contribution Guide
  • Reference Guide
Eclipse

Published at DZone with permission of Nikhil Nanivadekar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Domain-Driven Design: Manage Data With Jakarta Data and JNoSQL
  • Understanding and Learning NoSQL Databases With Java: Three Key Benefits
  • Achieving Inheritance in NoSQL Databases With Java Using Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!