Java 8 BinaryOperator Examples

In Java 8, BinaryOperator is a functional interface and it extends BiFunction. The BinaryOperator takes two arguments of the same type and returns a result of the same type of its arguments. BinaryOperator.java @FunctionalInterface public interface BinaryOperator<T> extends BiFunction<T,T,T> { } The BiFunction takes two arguments of any type, and returns a result of any …

Read more

Java 8 – How to Sum BigDecimal using Stream?

In Java 8, we can use the Stream.reduce() to sum a list of BigDecimal. 1. Stream.reduce() Java example to sum a list of BigDecimal values, using a normal for loop and a stream.reduce(). JavaBigDecimal.java package com.mkyong; import java.math.BigDecimal; import java.util.LinkedList; import java.util.List; public class JavaBigDecimal { public static void main(String[] args) { List<BigDecimal> invoices = …

Read more

Java 8 Stream.iterate examples

In Java 8, we can use Stream.iterate to create stream values on demand, so called infinite stream. 1. Stream.iterate 1.1 Stream of 0 – 9 //Stream.iterate(initial value, next value) Stream.iterate(0, n -> n + 1) .limit(10) .forEach(x -> System.out.println(x)); Output 0 1 2 3 4 5 6 7 8 9 1.2 Stream of odd numbers …

Read more

Java – How to sum all the stream integers

The sum() method is available in the primitive int-value stream like IntStream, not Stream<Integer>. We can use mapToInt() to convert a stream integers into a IntStream. int sum = integers.stream().mapToInt(Integer::intValue).sum(); int sum = integers.stream().mapToInt(x -> x).sum(); Full example. Java8Stream.java package com.mkyong.concurrency; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Java8Stream { public static void main(String[] …

Read more

Java 8 flatMap example

This article explains the Java 8 Stream.flatMap and how to use it. Topic What is flatMap? Why flat a Stream? flatMap example – Find a set of books. flatMap example – Order and LineItems. flatMap example – Splits the line by spaces. flatMap and Primitive type 1. What is flatMap()? 1.1 Review the below structure. …

Read more