Logo

dev-resources.site

for different kinds of informations.

Ways to filter list in java

Published at
4/23/2023
Categories
java
collections
filter
list
Author
pskolte84
Categories
4 categories in total
java
open
collections
open
filter
open
list
open
Author
9 person written this
pskolte84
open
Ways to filter list in java

List is commonly used Collection in Java. Many times List needs to be filtered by some attribute or property. Example: Filter the Employee list to get list of permanent employees only. There are many ways to filter list. This blog focus on filtering list with different criteria.

For filtering example we are considering list of Apples. List has mix of apples with red and green color with different weight and taste.

Lets create Apple class with color, weight and taste with getter and setters implemented.

package com.filter.fruits;

public class Apple {
    private int weight;
    private String color;
    private String taste;


    public Apple() {
        super();
    }

    public Apple(int weight, String color, String taste) {
        super();
        this.weight = weight;
        this.color = color;
        this.taste = taste;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getTaste() {
        return taste;
    }

    public void setTaste(String taste) {
        this.taste = taste;
    }

    @Override
    public String toString() {
        return "Apple [weight=" + weight + ", color=" + color + ", taste=" + taste + "]";
    }

}

Enter fullscreen mode Exit fullscreen mode

Lets create a utils class to get List of mixed Apples.

package com.filter.fruits;

import java.util.ArrayList;
import java.util.List;
//This class create methods for getting pre-filled list of apples
public class AppleUtils {
    public static List<Apple> getAppleList() {
        List<Apple> applesList = new ArrayList<>();
        applesList.add(new Apple(100, "Green", "Sour"));
        applesList.add(new Apple(200, "Red", "Sweet"));
        applesList.add(new Apple(150, "Green", "Sour"));
        applesList.add(new Apple(250, "Red", "Sweet"));
        applesList.add(new Apple(150, "Green", "Sour"));
        applesList.add(new Apple(150, "Red", "Sweet"));
        applesList.add(new Apple(200, "Green", "Sour"));
        return applesList;
    }

}

Enter fullscreen mode Exit fullscreen mode

Now, we need to create methods to filter out apples.
AppleFilterUtils has methods as below.

  • filterByRedColor methods filters by "Red" color which is not flexible
  • filterByGreenColor methods filters by "Gree" color which is not flexible
  • filterByColor methods filters by color which is passed from outside. This method can be used for green as red apple filtering
  • filterByColorAndWeight methods filters by color and weight by passing them from outside
  • filterByCritera methods filters criteria passed using Predicate class. Predicate class define criteria.
package com.filter.fruits;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class AppleFilterUtils {
    public static List<Apple> filterByRedColor(List<Apple> appleList){
        List<Apple> filteredList = new ArrayList<>();
        for(Apple apple : appleList) {
            if("Red".equals(apple.getColor())) {
                filteredList.add(apple);
            }
        }
        return filteredList;
    }

    public static List<Apple> filterByGreenColor(List<Apple> appleList){
        List<Apple> filteredList = new ArrayList<>();
        for(Apple apple : appleList) {
            if("Green".equals(apple.getColor())) {
                filteredList.add(apple);
            }
        }
        return filteredList;
    }

    public static List<Apple> filterByColor(List<Apple> appleList, String color){
        List<Apple> filteredList = new ArrayList<>();
        for(Apple apple : appleList) {
            if(color.equals(apple.getColor())) {
                filteredList.add(apple);
            }
        }
        return filteredList;
    }

    public static List<Apple> filterByColorAndWeight(List<Apple> appleList, String color, int weight){
        List<Apple> filteredList = new ArrayList<>();
        for(Apple apple : appleList) {
            if(color.equals(apple.getColor()) && weight >= apple.getWeight()) {
                filteredList.add(apple);
            }
        }
        return filteredList;
    }


    public static List<Apple> filterByCritera(List<Apple> appleList, Predicate<Apple> predicate){
        List<Apple> filteredList = new ArrayList<>();
        for(Apple apple : appleList) {
            if(predicate.test(apple)) {
                filteredList.add(apple);
            }
        }
        return filteredList;
    }

}

Enter fullscreen mode Exit fullscreen mode

Custom Predicates can be created by inheriting Predicate class.

Lets create Predicate for Green apples and another for filtering apples having weight more than 150g

package com.filter.fruits.predicates;

import java.util.function.Predicate;

import com.acts.fruits.Apple;

public class AppleColorPredicate implements Predicate<Apple>{


    @Override
    public boolean test(Apple t) {
        return "Green".equals(t.getColor());
    }

}

Enter fullscreen mode Exit fullscreen mode
package com.filter.fruits.predicates;

import java.util.function.Predicate;

import com.acts.fruits.Apple;

public class AppleWeightPredicate implements Predicate<Apple>{

    @Override
    public boolean test(Apple t) {
        return t.getWeight() > 150;
    }

}

Enter fullscreen mode Exit fullscreen mode

Lets take look at below Tester class to test Filter methods from AppleFilterUtils class

package com.acts.fruits.tester;

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.filter.fruits.Apple;
import com.filter.fruits.AppleFilterUtils;
import com.filter.fruits.AppleUtils;
import com.filter.fruits.predicates.AppleColorPredicate;
import com.filter.fruits.predicates.AppleWeightPredicate;

public class AppleFilterTester {

    public static void main(String[] args) {
        //Getting apple list from utils class
        List<Apple> applesList = AppleUtils.getAppleList();
        System.out.println("1.All Apples\n" + applesList);

        //Filter By Red color
        List<Apple> filteredList1 = AppleFilterUtils.filterByRedColor(applesList);
        System.out.println("2.Red apples\n" + filteredList1);

        //Filter By Green color
        List<Apple> filteredList2 = AppleFilterUtils.filterByGreenColor(applesList);
        System.out.println("3.Green apples\n" + filteredList2);

        //Passing color as parameter
        //Filter By color: Red
        List<Apple> filteredList3 = AppleFilterUtils.filterByColor(applesList, "Red");
        System.out.println("4.Red apples\n" + filteredList3);

        //Filter By color: Green
        List<Apple> filteredList4 = AppleFilterUtils.filterByColor(applesList, "Green");
        System.out.println("5.Green apples\n" + filteredList4);

        //Filter By color: Green and weight >150
        List<Apple> filteredList5 = AppleFilterUtils.filterByColorAndWeight(applesList, "Green", 150);
        System.out.println("6.Green apples\n" + filteredList5);

        // Using predicate from java8
        Predicate<Apple> appleColorPredicate =  new AppleColorPredicate();
        //Filter By color: Green  using predicate
        List<Apple> filteredList6 = AppleFilterUtils.filterByCritera(applesList, appleColorPredicate);
        System.out.println("7.Green apples\n" + filteredList6);

        // Using predicate from java8
        Predicate<Apple> appleWeightPredicate =  new AppleWeightPredicate();
        //Filter By weight > =150  using predicate
        List<Apple> filteredList7 = AppleFilterUtils.filterByCritera(applesList, appleWeightPredicate);
        System.out.println("8.With Weight apples\n" + filteredList7);

        // Using predicate from java8
        Predicate<Apple> predicate = (apple) ->  apple.getColor().equals("Red") && apple.getWeight() > 200;
        List<Apple> filteredList8 = AppleFilterUtils.filterByCritera(applesList, predicate);
        System.out.println("9.Red With Weight apples\n" + filteredList8);

        // Using predicate and stream api from java8
        List<Apple> filteredList9 = applesList.stream()
        .filter(predicate)
        .collect(Collectors.toList());
        System.out.println("10.Red With Weight apples\n" + filteredList9);


        // Using Stream and predicate on the fly and stream api from java8
        List<Apple> filteredList10 = applesList.stream()
                .filter((apple) ->  apple.getColor().equals("Green") && apple.getWeight() > 150)
                .collect(Collectors.toList());
        System.out.println("11.Freen With Weight apples\n" + filteredList10);

        // Using Stream and predicate on the fly and stream api from java8
        List<Apple> filteredList11 = applesList.stream()
                .filter((apple) ->  apple.getColor().equals("Green"))
                .filter((apple) ->  apple.getTaste().equals("Sweet"))
                .collect(Collectors.toList());
        System.out.println("12.Green With Taste apples\n" + filteredList11);


    }

}

Enter fullscreen mode Exit fullscreen mode
collections Article's
30 articles in total
Favicon
Introduction to Arrays
Favicon
Collections in Salesforce Apex
Favicon
Understanding Collections in .NET: A Guide to Simplicity and Abstraction
Favicon
Understanding the Need for Collections in Programming
Favicon
Explain Load Factors for ArrayList and HashMap in Java
Favicon
Generics in C#: Flexibility, Reusability, and Type Safety
Favicon
Explain internal working of HashMap in Java
Favicon
Common Java Libraries and Frameworks you Should Try
Favicon
What is the difference between HashMap and Hashtable?
Favicon
What are the differences between HashSet and TreeSet?
Favicon
Understanding the Difference Between pluck() and select() in Laravel 11
Favicon
Java Collections Scenario Based Interview Question
Favicon
Mastering Java Collections with Multithreading: Best Practices and Practical Examples
Favicon
Building Ansible Execution Environments with Non-Default Collections
Favicon
Average City Temperature Calculation Interview Question EPAM
Favicon
Enhancing Order in Java Collections with Sequenced Interface
Favicon
[Python] Collections.Counter
Favicon
Java Collections: Saiba quando usar Set, Map, List ou Queue.
Favicon
Ways to filter list in java
Favicon
A quick tour of collections in C#
Favicon
Collections en Java : ImplΓ©mentations et cas d'utilisation (List, Set et Map)
Favicon
#Rust πŸ¦€ – Working with hashmaps is cool. And a little C# experience πŸ˜„
Favicon
Create a Twitter RSS Feed With Upto 1000 Items (2023)
Favicon
HashMap in java
Favicon
How to Remove Duplicates from ArrayList in Java
Favicon
When to use LinkedList over ArrayList in Java ?
Favicon
Content Marketing Portfolio β€” A Step-by-Step Guide with Examples
Favicon
How to Create a PDF Portfolio & 5 Excellent PDF Portfolio Examples
Favicon
A Comprehensive Guide to Creating a Journalism Portfolio
Favicon
How to Build a Stunning Social Media Portfolio: A Step-by-Step Guide with Examples

Featured ones: