What is the best way to filter a Java Collection?

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

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

27条回答
  •  庸人自扰
    2020-11-21 07:39

    I'll throw RxJava in the ring, which is also available on Android. RxJava might not always be the best option, but it will give you more flexibility if you wish add more transformations on your collection or handle errors while filtering.

    Observable.from(Arrays.asList(1, 2, 3, 4, 5))
        .filter(new Func1() {
            public Boolean call(Integer i) {
                return i % 2 != 0;
            }
        })
        .subscribe(new Action1() {
            public void call(Integer i) {
                System.out.println(i);
            }
        });
    

    Output:

    1
    3
    5
    

    More details on RxJava's filter can be found here.

提交回复
热议问题