CollectionUtils select() Example in Java

In this post, we will see CollectionUtils select() example in Java. we will see how to use CollectionUtils select() method using org.apache.commons.collections4 Predicate.

We need to add the below dependency in maven to use org.apache.commons.lang3.CollectionUtils select() 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>

CollectionUtils select() Example in Java

package com.javatute.main;

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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CollectionUtilsSelectExample {
    public static void main(String[] args) {
        // Create first list
        List<String> list1 = new ArrayList<>();
        // add some element
        list1.add("John");
        list1.add("Mark");
        list1.add("Smith");
        list1.add("Twin");

        Collection<String> finalList = CollectionUtils.select(list1, new Predicate<String>() {
            @Override
            public boolean evaluate(String str) {
                return str.equals("Mark");
            }
        });

        System.out.println(finalList);
    }
}

Output is – [Mark]

That’s all about CollectionUtils select() Example in Java.

See docs

Related post