What is the best way to filter a Java Collection?

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

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

27条回答
  •  情深已故
    2020-11-21 07:25

    With the ForEach DSL you may write

    import static ch.akuhn.util.query.Query.select;
    import static ch.akuhn.util.query.Query.$result;
    import ch.akuhn.util.query.Select;
    
    Collection collection = ...
    
    for (Select each : select(collection)) {
        each.yield = each.value.length() > 3;
    }
    
    Collection result = $result();
    

    Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.

    All iteration styles supported by the ForEach DSL are

    • AllSatisfy
    • AnySatisfy
    • Collect
    • Counnt
    • CutPieces
    • Detect
    • GroupedBy
    • IndexOf
    • InjectInto
    • Reject
    • Select

    For more details, please refer to https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach

提交回复
热议问题