Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Collection Filtering In Java

DZone's Guide to

Collection Filtering In Java

·
Free Resource
// filtering a Collection


public class CollectionsFilter {
    public static void main(String[] args) {
        List
  
    list = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7,
                        8, 9, 10 });
        Collection
   
     evenNumbers = Utils.filter(list,
                        new Predicate
    
     () {
                                public boolean apply(Integer i) {
                                        if (i % 2 == 0) {
                                                return true;
                                        }
                                        return false;
                                }
                        });

        Collection
     
       oddNumbers = Utils.filter(list,
                        new Predicate
      
       () {
                                public boolean apply(Integer i) {
                                        if (i % 2 != 0) {
                                                return true;
                                        }
                                        return false;
                                }
                        });
        System.out.println("EVEN Numbers > " + evenNumbers);
        System.out.println("ODD Numbers > " + oddNumbers);
    }
}

      
     
    
   
  
Utils.filter() method :

public static 
  
    Collection
   
     filter(Collection
    
      target,
                Predicate
     
       predicate) {
  Collection
      
        filteredCollection = new ArrayList
       
        ();
   for (T t : target) {
     if (predicate.apply(t)) {
          filteredCollection.add(t);
     }
   }
   return filteredCollection;
}

       
      
     
    
   
  
and Predicate:

public interface Predicate
  
    {
    public boolean apply(T type);
}


  
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}