is there a Java equivalent to Javascript's “some” method?

前端 未结 4 1480
温柔的废话
温柔的废话 2021-02-19 16:58

I have a collection and I would like to know if at least one element meets some condition. Essentially, what some does in JavaScript, I would like to do on a collection!

4条回答
  •  走了就别回头了
    2021-02-19 17:35

    You can use CollectionUtils from Apache commons-collections:

    List primes = Arrays.asList(3, 5, 7, 11, 13)
    CollectionUtils.exists(primes, even);  //false
    

    Where even is a predicate:

    Predicate even = new Predicate() {
        public boolean evaluate(Object object) {
            return ((Integer)object) % 2 == 0;
        }
    }
    

    Or in an inlined version:

    List primes = Arrays.asList(2, 3, 5, 7, 11, 13)
    CollectionUtils.exists(primes, new Predicate() {
        public boolean evaluate(Object object) {
            return ((Integer)object) % 2 == 0;
        }
    });
    

    Yes, it is ugly for two reasons:

    1. Java does not (yet) support functions as first-class citizens, which are emulated with Single-Abstract-Method interface.
    2. commons-collections does not support generics.

    On the other hand in modern JVM languages like Scala you can write:

    List(3,5,7,11,13,17).exists(_ % 2 == 0)
    

提交回复
热议问题