There is a list of elements of the Event class.
@Data
@AllArgsConstructor
public class Event {
private Long id;
private String nameRu;
private String nameEn;
}
I want to get value of one field from an Event (any of the objects).
Event event1 = new Event(1, null, null);
Event event2 = new Event(2, null, null);
List<Event> events = new ArrayList<>();
events.add(event1);
events.add(event2);
int languageId = 1;
String name = events.stream().map(s -> {
if (languageId == 1)
return s.getNameEn();
else if (languageId == 2)
return s.getNameRu();
else return s.getNameEn();
}).findAny().orElse(null);
But if in each element this field has the value null, then stream.map() returns null (but it should return a stream of some number of nulls), and the findAny() call throws a NullPointerException.
Two questions:
- Why does the map() not return a stream if the map() is not terminal?
- How can I get the value of a field without exceptions?