Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 840
Aaron Silverman Avatar asked Jan 24 '12 17:01

Aaron Silverman


People also ask

Does Java have objects like JavaScript?

Object Oriented ProgrammingBoth Java and JavaScript are object oriented languages. While Java necessitates use of objects throughout the codebase, JavaScript is considerably more forgiving, allowing for simple linear programming without the use of objects.

What is some and every in JS?

every() method in JavaScript is used to check whether all the elements of the array satisfy the given condition or not. The Array. some() method in JavaScript is used to check whether at least one of the elements of the array satisfies the given condition or not.

What is some function in JavaScript?

some() The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.


1 Answers

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");
        }
    }
}
like image 90
user1460043 Avatar answered Oct 21 '22 01:10

user1460043