How to iterate with foreach loop over java 8 stream

By definition foreach loop requires an Iterable to be passed in. It can be achieved with anonymous class: for (String s : new Iterable<String>() { @Override public Iterator<String> iterator() { return stream.iterator(); } }) { writer.append(s); } This can be simplified with lambda because Iterable is a functional interface: for (String s : (Iterable<String>) () … Read more

Java8 Adding Hours To LocalDateTime Not Working

The documentation of LocalDateTime specifies the instance of LocalDateTime is immutable, for example plusHours public LocalDateTime plusHours(long hours) Returns a copy of this LocalDateTime with the specified number of hours added. This instance is immutable and unaffected by this method call. Parameters: hours – the hours to add, may be negative Returns: a LocalDateTime based … Read more

java.lang.ClassCastException using lambda expressions in spark job on remote server

What you have here, is a follow-up error which masks the original error. When lambda instances are serialized, they use writeReplace to dissolve their JRE specific implementation from the persistent form which is a SerializedLambda instance. When the SerializedLambda instance has been restored, its readResolve method will be invoked to reconstitute the appropriate lambda instance. … Read more

java.lang.ClassCastException using lambda expressions in spark job on remote server

What you have here, is a follow-up error which masks the original error. When lambda instances are serialized, they use writeReplace to dissolve their JRE specific implementation from the persistent form which is a SerializedLambda instance. When the SerializedLambda instance has been restored, its readResolve method will be invoked to reconstitute the appropriate lambda instance. … Read more

Hibernate 4 with java.time.LocalDate and DATE() construct

If you use JPA 2.1 this is simple to do. Converters allow your JPA entities to use the new java.time.LocalDate and java.time.LocalDateTime classes. Simply define the needed converter classes: LocalDatePersistenceConverter.java import java.time.LocalDate; import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class LocalDatePersistenceConverter implements AttributeConverter<LocalDate, java.sql.Date> { @Override public java.sql.Date convertToDatabaseColumn(LocalDate entityValue) { if (entityValue != null) { … Read more

Java 8 stream average for float

To answer the second part of your question, if you want to avoid the exception when the list is empty and return some double value, use orElse instead of getAsDouble: return weightChanges.stream() .mapToDouble(WeightChange::getValue) .average() .orElse(Double.NaN);