简体   繁体   中英

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!

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

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM