What is the best way to filter a Java Collection?

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

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

27条回答
  •  没有蜡笔的小新
    2020-11-21 07:20

    This, combined with the lack of real closures, is my biggest gripe for Java. Honestly, most of the methods mentioned above are pretty easy to read and REALLY efficient; however, after spending time with .Net, Erlang, etc... list comprehension integrated at the language level makes everything so much cleaner. Without additions at the language level, Java just cant be as clean as many other languages in this area.

    If performance is a huge concern, Google collections is the way to go (or write your own simple predicate utility). Lambdaj syntax is more readable for some people, but it is not quite as efficient.

    And then there is a library I wrote. I will ignore any questions in regard to its efficiency (yea, its that bad)...... Yes, i know its clearly reflection based, and no I don't actually use it, but it does work:

    LinkedList list = ......
    LinkedList filtered = 
               Query.from(list).where(Condition.ensure("age", Op.GTE, 21));
    

    OR

    LinkedList list = ....
    LinkedList filtered = Query.from(list).where("x => x.age >= 21");
    

提交回复
热议问题