How can I 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

Collectors.summingInt() vs mapToInt().sum()

You are looking at the intersection of two otherwise distinct use cases. Using mapToInt(…) allows you to chain other IntStream operations before the terminal operation. In contrast, Collectors.summingInt(…) can be combined with other collectors, e.g. used as downstream collector in a groupingBy collector. For these use cases, there is no question about which to use. … Read more

Iterate two Java-8-Streams together [duplicate]

static <A, B> Stream<Pair<A, B>> zip(Stream<A> as, Stream<B> bs) { Iterator<A> i=as.iterator(); return bs.filter(x->i.hasNext()).map(b->new Pair<>(, b)); } This does not offer parallel execution but neither did the original zip implementation. And as F. Böller has pointed out it doesn’t work if bs is infinite and as is not. For a solution which works for all … Read more

Recursive use of Stream.flatMap()

Well, I used the same pattern with a generic Tree class and didn’t have a wrong feeling with it. The only difference is, that the Tree class itself offered a children() and allDescendants() methods, both returning a Stream and the latter building on the former. This is related to “Should I return a Collection or … Read more

Why can’t I throw an exception in a Java 8 lambda expression? [duplicate]

You are not allowed to throw checked exceptions because the accept(T t, U u) method in the java.util.function.BiConsumer<T, U> interface doesn’t declare any exceptions in its throws clause. And, as you know, Map#forEach takes such a type. public interface Map<K, V> { default void forEach(BiConsumer<? super K, ? super V> action) { … } } … Read more