FirstOrDefault C# Lambda to Java 8 Lambda


While converting c# code to java there are several lambdas that c# has that were a little difficult to find a port to java. One of these was C Sharp’s FirstOrDefault lambda expression. Java has an equivalent stream. We can use the findFirst and if it doesn’t find anything then we can return a null. This in essence is the same as the method in c# – return first or null unless I specify otherwise. While the java version is slightly more verbose, the functionality is the same.

 if (birth == null) birth = person.Events.FirstOrDefault(e => e.Type.GetGeneralEventType() == EventType.Birth); // Use a christening, etc.
if (birth == null) birth = person.getEvents().stream().filter(event -> event.getType().getGeneralEventType() == EventType.Birth).findFirst().orElse(null);// Use a christening, etc.


Comments are closed.