Consider following ArrayList:
[0] => Person
[1] => User
[2] => Dummy
How can one with Java streams check if this arraylist contains any other objects than Person
or User
?
So that I can make an if statement to return null if it contains only Person
and User
, or return the arraylist itself if it contains any other objects besides Person
or User
like so:
if( /*arrayList contains only Person and User*/ ) {
return null;
}
else {
//arrayList contains other objects besides Person and User
return arrayList;
}
Using Stream anyMatch() Method If you are using Java 8 or higher, you can create a stream from the array. Then use the anyMatch() method with a lambda expression to check if it contains a given value.
ArrayList. contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.
The stream() method on an ArrayList instance returns a Stream object with a matching type. However Stream() does not return an IntStream or DoubleStream, even when those types are present. So We must use the stream() directly when we get it from an ArrayList. We "cannot cast from a Stream(int) to an IntStream."
Assuming Person
and User
are types, rather than specific objects, you can do something like this.
return list.stream()
.filter(o -> !(o instanceof Person) && !(o instanceof User))
.findAny()
.isPresent() ? list : null;
Alternative to Paul's answer (with the if-else in your question)
if (arrayList.stream().allMatch(o -> o instanceof Person || o instanceof User)) {
return null;
} else {
return arrayList;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With