Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream API. Find field of an object matching predicate in one line. Return some default value if not exists

For example, we have a simple class with some fields. Let's assume, we have fields called 'name' and 'id'. And I want to get name of an object with specified id and return some defaultName, if there is no such object:

private List<MyObject> myObjects;
public String findFieldById(int id) {
    MyObject matchingObj = myObjects.stream()
                    .filter(m -> m.getId() == id)
                    .findFirst().orElse(null);

    return (matchingObj == null) ? "defaultName" : matchingObj.getName();
}

My question is how can I easily make this check on null in a stream in one line?

like image 560
scenotaph Avatar asked Jan 08 '19 12:01

scenotaph


People also ask

What is findFirst in Java stream?

Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

How do you check if a value is present in list of objects in Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

What does stream of () method in Java?

Stream of(T t) returns a sequential Stream containing a single element. Syntax : static Stream of(T t) Parameters: This method accepts a mandatory parameter t which is the single element in the Stream. Return Value: Stream of(T t) returns a sequential Stream containing the single specified element.


1 Answers

You can perform this type of operation in one pipeline by mapping to MyObject::getName after findFirst otherwise provide a default value via orElse.

return myObjects.stream()
         .filter(m -> m.getId() == id)
         .findFirst()
         .map(MyObject::getName)
         .orElse("defaultName");
like image 175
Ousmane D. Avatar answered Nov 06 '22 12:11

Ousmane D.