Java 8 Lambda function that throws exception?

You’ll need to do one of the following. If it’s your code, then define your own functional interface that declares the checked exception: @FunctionalInterface public interface CheckedFunction<T, R> { R apply(T t) throws IOException; } and use it: void foo (CheckedFunction f) { … } Otherwise, wrap Integer myMethod(String s) in a method that doesn’t … Read more

Does a lambda expression create an object on the heap every time it’s executed?

It is equivalent but not identical. Simply said, if a lambda expression does not capture values, it will be a singleton that is re-used on every invocation. The behavior is not exactly specified. The JVM is given big freedom on how to implement it. Currently, Oracle’s JVM creates (at least) one instance per lambda expression … Read more

Is there a concise way to iterate over a stream with indices in Java 8?

The cleanest way is to start from a stream of indices: String[] names = {“Sam”, “Pamela”, “Dave”, “Pascal”, “Erik”}; IntStream.range(0, names.length) .filter(i -> names[i].length() <= i) .mapToObj(i -> names[i]) .collect(Collectors.toList()); The resulting list contains “Erik” only. One alternative which looks more familiar when you are used to for loops would be to maintain an ad … Read more

How to parse/format dates with LocalDateTime? (Java 8)

Parsing date and time To create a LocalDateTime object from a string you can use the static LocalDateTime.parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern. String str = “1986-04-08 12:30”; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm”); LocalDateTime dateTime = LocalDateTime.parse(str, formatter); Formatting date and … Read more

What’s the difference between Instant and LocalDateTime?

tl;dr Instant and LocalDateTime are two entirely different animals: One represents a moment, the other does not. Instant represents a moment, a specific point in the timeline. LocalDateTime represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of … Read more