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

前端 未结 4 1504
温柔的废话
温柔的废话 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 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");
            }
        }
    }
    

提交回复
热议问题