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

前端 未结 4 1479
温柔的废话
温柔的废话 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:41

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

提交回复
热议问题