allMatch, anyMatch on lists without creating streams

359
April 23, 2017, at 08:35 AM

It bothers me (for performance reasons) that I can't call allMatch, anyMatch on lists without first creating streams. So I started creating utility methods like this:

public static <T> boolean anyMatch(List<T> list, Predicate<T> predicate) {
    for (T element : list) {
        if (predicate.test(element)) {
            return true;
        }
    }
    return false;
}

Is there no easier way?

EDIT I'm not just worried about the cost of a single object. If you look at the source of Stream.anyMatch, you can see that a lot of things happen which are not necessary in this simple case.

Answer 1

Your new method seems a good idea. Although it would be better if you use Decorator Pattern instead of a utility method just to maintain a good Object Oriented Design.

public class StreamList<T> {
 List<T> list;
 public StreamList(List list) {
  this.list = list;
 }
 public boolean anyMatch(Predicate<T> predicate) {
    for (T element : list) {
        if (predicate.test(element)) {
            return true;
        }
    }
    return false;
 }
}
READ ALSO
error: cannot find symbol, won&#39;t find my bean

error: cannot find symbol, won't find my bean

I was given code that I have to make do something elseWhen I go to compile my servlet, it doesn't recognize my bean

346
Is it possible to upload data to read only bucket on amazon s3 using java sdk

Is it possible to upload data to read only bucket on amazon s3 using java sdk

The bucket is in this region: nullPlease use this region to retry the request (Service: Amazon S3; Status Code: 301; Error Code: PermanentRedirect; Request ID: 437E211C5EDD014D)

273
How do I take an array of objects and update the object data file after changing variables in the array?

How do I take an array of objects and update the object data file after changing variables in the array?

I have an array of objects and I am trying to change the values of the objects and then re-update the storage file where the object-in-file are storedWhen I try changing the storage file it either clears the file or does nothing

281
Compile error using array and ints

Compile error using array and ints

I am getting the compile error and I don't understand why or how to fix it,

311