What is the best way to filter a Java Collection?

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

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

27条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:27

    The simple pre-Java8 solution:

    ArrayList filtered = new ArrayList(); 
    for (Item item : items) if (condition(item)) filtered.add(item);
    

    Unfortunately this solution isn't fully generic, outputting a list rather than the type of the given collection. Also, bringing in libraries or writing functions that wrap this code seems like overkill to me unless the condition is complex, but then you can write a function for the condition.

提交回复
热议问题