What is the best way to filter a Java Collection?

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

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

27条回答
  •  攒了一身酷
    2020-11-21 07:21

    My answer builds on that from Kevin Wong, here as a one-liner using CollectionUtils from spring and a Java 8 lambda expression.

    CollectionUtils.filter(list, p -> ((Person) p).getAge() > 16);
    

    This is as concise and readable as any alternative I have seen (without using aspect-based libraries)

    Spring CollectionUtils is available from spring version 4.0.2.RELEASE, and remember you need JDK 1.8 and language level 8+.

提交回复
热议问题