CollectionUtils collect() Example in Java

The collect() method in the CollectionUtils class from the Apache Commons Collection library is used to collect elements from a collection and add them to a target collection. In this post, we will see CollectionUtils collect() example in Java. we will see how to use CollectionUtils collect() method.

We need to add the below dependency in maven to use org.apache.commons.lang3.CollectionUtils collect() method. We can download the apache-commons maven dependency from here.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>

How to use collect() method

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;

import java.util.List;
import java.util.Set;
import java.util.HashSet;

public class CollectExample {

    public static void main(String[] args) {
        List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Set<Integer> evenNumbers = new HashSet<>();

        CollectionUtils.collect(numbers, new Predicate<Integer>() {
            @Override
            public boolean evaluate(Integer number) {
                return number % 2 == 0;
            }
        }, evenNumbers);

        System.out.println("Even numbers: " + evenNumbers);
    }
}

In this example, the collect() method is used to iterate over the elements in the numbers list, and the Predicate passed as the second argument is used to evaluate each element. If the evaluation returns true, the element is added to the evenNumbers set. After the collection is complete, the evenNumbers set will contain all the even numbers from the original numbers list.

Note:- Method collect() is used to marge names List1 and List2.

That’s all about CollectionUtils collect() example in Java.

Related post.