What is the best way to filter a Java Collection?

后端 未结 27 3390
故里飘歌
故里飘歌 2020-11-21 06:55

I want to filter a java.util.Collection based on a predicate.

27条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 07:26

    I wrote an extended Iterable class that support applying functional algorithms without copying the collection content.

    Usage:

    List myList = new ArrayList(){ 1, 2, 3, 4, 5 }
    
    Iterable filtered = Iterable.wrap(myList).select(new Predicate1()
    {
        public Boolean call(Integer n) throws FunctionalException
        {
            return n % 2 == 0;
        }
    })
    
    for( int n : filtered )
    {
        System.out.println(n);
    }
    

    The code above will actually execute

    for( int n : myList )
    {
        if( n % 2 == 0 ) 
        {
            System.out.println(n);
        }
    }
    

提交回复
热议问题