DEV Community

Praphul Kolte
Praphul Kolte

Posted on

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

Top comments (0)