java.lang.NullPointerException is thrown using a method-reference but not a lambda expression

This behaviour relies on a subtle difference between the evaluation process of method-references and lambda expressions. From the JLS Run-Time Evaluation of Method References: First, if the method reference expression begins with an ExpressionName or a Primary, this subexpression is evaluated. If the subexpression evaluates to null, a NullPointerException is raised, and the method reference …

Read more

Simplest way to print an `IntStream` as a `String`

String result = “Hello world.” .codePoints() //.parallel() // uncomment this line for large strings .map(c -> c == ‘ ‘ ? ‘ ‘: ‘*’) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); But still, “Hello world.”.replaceAll(“[^ ]”, “*”) is simpler. Not everything benefits from lambdas.

Convert String array to Map using Java 8 Lambda expressions

You can modify your solution to collect the Stream of String arrays into a Map (instead of using forEach) : Map<String, Double> kvs = Arrays.asList(“a:1.0”, “b:2.0”, “c:3.0”) .stream() .map(elem -> elem.split(“:”)) .collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1]))); Of course this solution has no protection against invalid input. Perhaps you should add a filter just in …

Read more

Close Java 8 Stream

It is generally not necessary to close streams at all. You only need to close streams that use IO resources. From the Stream documentation: Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel …

Read more

JPA support for Java 8 new date and time API

For Hibernate 5.X just add <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-java8</artifactId> <version>${hibernate.version}</version> </dependency> and @NotNull @Column(name = “date_time”, nullable = false) protected LocalDateTime dateTime; will work without any additional effort. See https://hibernate.atlassian.net/browse/HHH-8844 UPDATE: Please have a look at Jeff Morin comment: since Hibernate 5.2.x it is enough <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.1.Final</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-…</artifactId> <version>4.3.1.RELEASE</version> </dependency> See …

Read more