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

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

    As of Java 8, you can convert the Collection into a Stream and use anyMatch as in the following example.

    import java.util.Arrays;
    import java.util.List;
    
    public class SomeExample {
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, -6, 7);
            boolean hasNegative = list.stream().anyMatch(x -> x < 0);
            if (hasNegative) {
                System.out.println("List contains some negative number");
            }
            else {
                System.out.println("List does not contain any negative number");
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-19 17:35

    You can use CollectionUtils from Apache commons-collections:

    List<Integer> 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<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, 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)
    
    0 讨论(0)
  • 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<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");
    
    0 讨论(0)
  • 2021-02-19 17:41

    Java doesn't have this feature built-in. Javascript's some() accepts a function pointer as an argument, which is not something that's natively supported in Java. But it should be fairly straight forward to emulate the functionality of some() in Java using a loop and and an interface for the callback functionality.

    0 讨论(0)
提交回复
热议问题