Search code examples
javajavascriptcollectionsguava

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


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!


Solution

  • Check out Guava's Iterables class and its any() implementation.

    More or less the same thing as the Commons Collections example in the other answer, but genericized:

    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");