Is there a Java equivalent of Javascript "some" method?

I have a collection, and I would like to know if at least one element satisfies certain conditions. In fact, that some is in JavaScript, I would like to do this in a collection!

+5
source share
3 answers

Check out the Guava Iterables class and any().

More or less the same as the example of Commons Collections in another answer, but generalized:

List<String> strings = Arrays.asList("ohai", "wat", "fuuuu", "kthxbai");
boolean well = Iterables.any(strings, new Predicate<String>() {
    @Override public boolean apply(@Nullable String s) {
        return s.equalsIgnoreCase("fuuuu");
    }
});
System.out.printf("Do any match? %s%n", well ? "Yep" : "Nope");
+16
source

You can use collective collectionsCollectionUtils from Apache :

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

Where evenis the predicate:

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

Or in the embedded version:

List<Integer> 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 he ugly for two reasons:

  • Java , .
  • commons-collections .

, JVM, Scala, :

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

Java does not have a built-in function. Javascriptsome() takes a function pointer as an argument, which is not a part supported in Java. But it should be pretty easy to emulate functionality some()in Java, using a loop and interface for the callback function.

0
source

All Articles