Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check ArrayList content with Java stream

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;
}
like image 932
henrik Avatar asked Nov 05 '15 15:11

henrik


People also ask

How do you check if a list contains a value in Java stream?

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.

How do I check if an ArrayList contains?

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.

What does ArrayList stream () do?

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."


2 Answers

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;
like image 89
Paul Boddington Avatar answered Sep 23 '22 07:09

Paul Boddington


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;
}
like image 29
Manos Nikolaidis Avatar answered Sep 23 '22 07:09

Manos Nikolaidis